Skip to content

World's first open-source enterprise world model.

A date is written at the precision it was recorded (#414)

WaylandYang92e07f421ff7
diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rs
index 5d824d49..cefa5945 100644
--- a/crates/utopia-server/src/api/chat.rs
+++ b/crates/utopia-server/src/api/chat.rs
@@ -110,7 +110,7 @@ pub(super) fn tools_schema(can_write: bool, data_source_names: &[String]) -> ser
"occurred_at": {
"type": "string",
"description": "Optional date the stated fact took effect \
- (YYYY-MM-DD). Omit to use today."
+ (YYYY, YYYY-MM, YYYY-MM-DD or RFC3339). Omit to use today."
}
},
"required": ["text"]
@@ -358,11 +358,11 @@ pub(super) fn base_tools() -> serde_json::Value {
"properties": {
"since": {
"type": "string",
- "description": "Start of the window (YYYY-MM-DD), inclusive."
+ "description": "Start of the window (YYYY, YYYY-MM or YYYY-MM-DD), inclusive — a year or month means its first day."
},
"until": {
"type": "string",
- "description": "End of the window (YYYY-MM-DD), inclusive of that whole day. Omit for 'up to now'."
+ "description": "End of the window (YYYY, YYYY-MM or YYYY-MM-DD), inclusive of that whole day, month or year. Omit for 'up to now'."
},
"entity_id": {
"type": "string",
@@ -416,7 +416,10 @@ const SYSTEM_PROMPT: &str = "You are the assistant of Utopia, a temporal knowled
when useful.\n\
2. Facts carry validity ranges (from → to). For \"as of <date>\" questions pass `at` to \
entity_facts and the server filters to that moment; for history questions omit `at` \
- to see the full timeline. For 'what did we know / have on record / believe as of <date>' or 'before <memo> arrived' pass `as_of` — that is the record axis and the ONLY way to answer such a question; do not narrate a plan, call the tool. The two combine: `at` for the date asked about, `as_of` for when. State dates in the answer.\n\
+ to see the full timeline. For 'what did we know / have on record / believe as of <date>' or 'before <memo> arrived' pass `as_of` — that is the record axis and the ONLY way to answer such a question; do not narrate a plan, call the tool. The two combine: `at` for the date asked about, `as_of` for when. State dates in the answer. Dates in tool output carry their own precision: \
+ `2023` means the year and `2023-06` the month — never turn them into a specific day; \
+ `attested <time>` marks a fact with no stated start, known only from that evidence on; \
+ `ended by <time>` marks one the text says is over, date not given.\n\
2a. For 'before a correction or memo arrived', call changes to find its exact record timestamp, \
then call entity_facts with `as_of` one microsecond before that timestamp. At the timestamp \
itself the change already applies. Preserve fractional seconds: for example, before \
diff --git a/crates/utopia-server/src/api/review_routes.rs b/crates/utopia-server/src/api/review_routes.rs
index 7a2816a5..75e62c6a 100644
--- a/crates/utopia-server/src/api/review_routes.rs
+++ b/crates/utopia-server/src/api/review_routes.rs
@@ -135,6 +135,25 @@ pub async fn list(
#[derive(Deserialize)]
pub struct CloseFactBody {
pub valid_to: chrono::DateTime<chrono::Utc>,
+ /// year | month | day。**写多少位就是多少精度**(与图谱页的区间编辑同一约定);
+ /// 不给按日——只发日期的老客户端就是这个意思
+ #[serde(default)]
+ pub valid_to_precision: Option<String>,
+}
+
+/// 人给的世界轴精度。从前这里一律写 "day"(「人在界面上选的是一个日期」),于是
+/// 「2023 年 6 月结束」只能编成 6 月 1 日——在无知的地方填一个确定的值,正是
+/// `facts.valid_to_precision` 那条注释说的病
+fn world_precision(p: Option<&str>) -> Result<&'static str, utopia_core::AppError> {
+ match p {
+ None | Some("day") => Ok("day"),
+ Some("month") => Ok("month"),
+ Some("year") => Ok("year"),
+ Some(_) => Err(utopia_core::AppError::invalid(
+ "bad_precision",
+ "A closing date's precision is year, month or day.",
+ )),
+ }
}
/// 人工闭合一条事实的有效区间("这事在某时结束了")——走作废+改写,
@@ -159,11 +178,13 @@ pub async fn close_fact(
if ok.is_none() {
return Err(utopia_core::AppError::NotFound.into());
}
+ let precision = world_precision(body.valid_to_precision.as_deref())?;
let snap = fact_snapshot(&state, kb_id, fact_id).await;
- // 人在界面上选的是一个日期,所以闭合点按日
- utopia_store::temporal::close_superseded(&state.pool, fact_id, body.valid_to, "day").await?;
+ utopia_store::temporal::close_superseded(&state.pool, fact_id, body.valid_to, precision)
+ .await?;
if let Some(mut d) = snap {
d["valid_to"] = json!(body.valid_to.to_rfc3339());
+ d["valid_to_precision"] = json!(precision);
let _ = utopia_store::audit::record(
&state.pool,
Some(kb_id),
@@ -186,6 +207,9 @@ pub struct ConflictBody {
/// close 且新事实无起点时必填
#[serde(default)]
pub close_at: Option<chrono::DateTime<chrono::Utc>>,
+ /// `close_at` 的精度(year | month | day),不给按日
+ #[serde(default)]
+ pub close_at_precision: Option<String>,
}
/// 时态冲突裁决(S3:自动闭合拿不准的那些)。
@@ -216,12 +240,14 @@ pub async fn resolve_conflict(
.await
.ok()
.flatten();
+ let close_precision = world_precision(body.close_at_precision.as_deref())?;
utopia_store::temporal::resolve_conflict(
&state.pool,
kb_id,
conflict_id,
&body.action,
body.close_at,
+ close_precision,
)
.await?;
if let Some((os, oo, ns, no, pred)) = snap {
@@ -242,6 +268,7 @@ pub async fn resolve_conflict(
"old_subject": os, "old_object": oo,
"new_subject": ns, "new_object": no,
"close_at": body.close_at.map(|t| t.to_rfc3339()),
+ "close_at_precision": body.close_at.map(|_| close_precision),
}),
)
.await;
@@ -518,6 +545,9 @@ pub struct DecideViolationReq {
/// `fact_closed` 必填:旧断言在哪一天结束
#[serde(default)]
pub close_at: Option<chrono::DateTime<chrono::Utc>>,
+ /// `close_at` 的精度(year | month | day),不给按日
+ #[serde(default)]
+ pub close_at_precision: Option<String>,
/// `fact_retracted` 时撤哪条:双事实与环上的违规必填,单事实的可省(#202)
#[serde(default)]
pub fact_id: Option<Uuid>,
@@ -621,10 +651,12 @@ pub async fn decide_violation(
)
.into());
}
+ let precision = world_precision(req.close_at_precision.as_deref())?;
let snap = fact_snapshot(&state, kb_id, left).await;
- utopia_store::temporal::close_superseded(&state.pool, left, at, "day").await?;
+ utopia_store::temporal::close_superseded(&state.pool, left, at, precision).await?;
if let Some(mut d) = snap {
d["valid_to"] = json!(at.to_rfc3339());
+ d["valid_to_precision"] = json!(precision);
let _ = utopia_store::audit::record(
&state.pool,
Some(kb_id),
diff --git a/crates/utopia-server/src/api/tools.rs b/crates/utopia-server/src/api/tools.rs
index cad491f6..5601d1ea 100644
--- a/crates/utopia-server/src/api/tools.rs
+++ b/crates/utopia-server/src/api/tools.rs
@@ -209,7 +209,7 @@ pub async fn get_document(
let when = doc
.doc_time
- .map(|t| t.format("%Y-%m-%d").to_string())
+ .map(crate::time_text::instant)
.unwrap_or_else(|| "no date".to_string());
let header = format!(
"\"{}\" ({when}) — {} section(s):",
@@ -347,7 +347,7 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolRe
Some(t) => format!(
"{}: no facts valid as of {}.",
node.name,
- t.format("%Y-%m-%d")
+ crate::time_text::instant(t)
),
None => format!("{}: no recorded facts.", node.name),
}
@@ -499,14 +499,17 @@ pub async fn rule_matches(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolRe
}
pub async fn changes(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult {
- let day = |k: &str| {
- args[k]
- .as_str()
- .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
- };
- let Some((since, until, window)) =
- changes_window(day("since"), day("until"), chrono::Utc::now())
- else {
+ // 两端与 `at` 同一种写法:YYYY / YYYY-MM / YYYY-MM-DD。`since` 取那一段的第一天,
+ // `until` 取最后一天——「2023 年有什么变化」不该逼模型编一个 12 月 31 日
+ let since = args["since"]
+ .as_str()
+ .and_then(utopia_extract::parse_time)
+ .map(|(t, _)| t.date_naive());
+ let until = args["until"]
+ .as_str()
+ .and_then(utopia_extract::parse_time)
+ .map(|(t, p)| period_last_day(t.date_naive(), p));
+ let Some((since, until, window)) = changes_window(since, until, chrono::Utc::now()) else {
return (
"Invalid or missing `since` (expected YYYY-MM-DD).".to_string(),
json!({ "kind": "changes", "label": "?", "detail": "invalid since" }),
@@ -585,11 +588,27 @@ pub async fn query_data(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResu
pub async fn remember(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult {
let text = args["text"].as_str().map(str::trim).unwrap_or("");
- let occurred_at = args["occurred_at"]
- .as_str()
- .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
- .map(|d| d.and_hms_opt(12, 0, 0).unwrap().and_utc())
- .unwrap_or_else(chrono::Utc::now);
+ // 与 `at` 同一种写法:YYYY / YYYY-MM / YYYY-MM-DD 或 RFC3339。日期落在那段第一天的
+ // 正午——离两边的日界都最远;时刻照给的。回显按给的精度写,不把「2023 年」说成 1 月 1 日
+ let (occurred_at, occurred_text) = match args["occurred_at"].as_str().map(str::trim) {
+ Some(s) if !s.is_empty() => match utopia_extract::parse_time(s) {
+ Some((d, precision)) => (
+ d + chrono::Duration::hours(12),
+ crate::time_text::world(d, Some(precision)),
+ ),
+ None => match parse_when(s) {
+ Some(at) => (at, crate::time_text::instant(at)),
+ None => {
+ let now = chrono::Utc::now();
+ (now, crate::time_text::instant(now))
+ }
+ },
+ },
+ _ => {
+ let now = chrono::Utc::now();
+ (now, crate::time_text::instant(now))
+ }
+ };
if text.is_empty() {
return (
"remember requires non-empty text.".to_string(),
@@ -620,7 +639,7 @@ pub async fn remember(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult
before entering the graph. Tell the user exactly that: the sentence is \
recorded, and the extracted facts await their confirmation. Do not claim \
any fact has been added to the knowledge graph.",
- occurred_at.format("%Y-%m-%d")
+ occurred_text
),
json!({
"kind": "tool", "label": "remember",
@@ -712,20 +731,27 @@ fn fact_line(f: &EntityFact) -> String {
} else {
format!("{pred} ← {other}")
};
- let range = match (&f.valid_from, &f.valid_to) {
- (Some(from), Some(to)) => {
- format!(" ({} → {})", from.format("%Y-%m-%d"), to.format("%Y-%m-%d"))
- }
- (Some(from), None) => format!(" ({} → now)", from.format("%Y-%m-%d")),
- (None, Some(to)) => format!(" (→ {})", to.format("%Y-%m-%d")),
- (None, None) => String::new(),
+ // 两端各按自己的精度写;没起点的从证据起,结束了不知哪天的到说出它的那份文档为止
+ //(time_text,0022)。从前一律 %Y-%m-%d,年精度印成 1 月 1 日、结束未知印成 now
+ let range = crate::time_text::span(crate::time_text::Span {
+ valid_from: f.valid_from,
+ from_precision: f.valid_from_precision.as_deref(),
+ valid_to: f.valid_to,
+ to_precision: f.valid_to_precision.as_deref(),
+ holds_from: f.holds_from,
+ holds_to: f.holds_to,
+ });
+ let range = if range.is_empty() {
+ range
+ } else {
+ format!(" ({range})")
};
format!("{core}{range} [{}%]", (f.confidence * 100.0).round() as i32)
}
// 记录轴上的两次更正可以发生在同一秒;输出必须能原样交回 as_of,不能截到天或秒。
fn record_stamp(time: chrono::DateTime<chrono::Utc>) -> String {
- time.to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true)
+ crate::time_text::instant(time)
}
fn entity_facts_detail(
@@ -736,10 +762,10 @@ fn entity_facts_detail(
match (at, as_of) {
(Some(t), Some(r)) => format!(
"{count} facts at {}, as recorded by {}",
- t.format("%Y-%m-%d"),
+ record_stamp(t),
record_stamp(r)
),
- (Some(t), None) => format!("{count} facts as of {}", t.format("%Y-%m-%d")),
+ (Some(t), None) => format!("{count} facts as of {}", record_stamp(t)),
(None, Some(r)) => format!("{count} facts as recorded by {}", record_stamp(r)),
(None, None) => format!("{count} facts"),
}
@@ -749,8 +775,9 @@ fn entity_facts_detail(
/// 时刻常常是一个带时间的戳("第一波灌完那一刻"),日期粒度装不下它
fn parse_when(raw: &str) -> Option<chrono::DateTime<chrono::Utc>> {
let s = raw.trim();
- if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
- return Some(d.and_hms_opt(0, 0, 0).unwrap().and_utc());
+ // YYYY / YYYY-MM / YYYY-MM-DD 取那一段的开头——与抽取端同一个解析
+ if let Some((d, _)) = utopia_extract::parse_time(s) {
+ return Some(d);
}
chrono::DateTime::parse_from_rfc3339(s)
.ok()
@@ -801,6 +828,25 @@ fn literal_text(v: &serde_json::Value) -> Option<String> {
/// 一起被测住;分在两处写,迟早再次分叉。
///
/// `now` 从外面传进来而不是在里面取,纯粹是为了这个函数测得动。
+/// 一段(年 / 月 / 日)的最后一天:`until=2023` 是到 12 月 31 日为止,含那一整天。
+fn period_last_day(first: chrono::NaiveDate, precision: &str) -> chrono::NaiveDate {
+ use chrono::Datelike;
+ match precision {
+ "year" => chrono::NaiveDate::from_ymd_opt(first.year(), 12, 31).unwrap_or(first),
+ "month" => {
+ let (y, m) = if first.month() == 12 {
+ (first.year() + 1, 1)
+ } else {
+ (first.year(), first.month() + 1)
+ };
+ chrono::NaiveDate::from_ymd_opt(y, m, 1)
+ .and_then(|d| d.pred_opt())
+ .unwrap_or(first)
+ }
+ _ => first,
+ }
+}
+
fn changes_window(
since: Option<chrono::NaiveDate>,
until: Option<chrono::NaiveDate>,
@@ -841,17 +887,19 @@ fn change_line(c: &GraphChange) -> String {
(None, Some(v)) => literal_text(v).unwrap_or_else(|| "?".to_string()),
(None, None) => "?".to_string(),
};
- let range = match (&c.valid_from, &c.valid_to) {
- (Some(from), Some(to)) => {
- format!(
- " [valid {} → {}]",
- from.format("%Y-%m-%d"),
- to.format("%Y-%m-%d")
- )
- }
- (Some(from), None) => format!(" [valid {} → now]", from.format("%Y-%m-%d")),
- (None, Some(to)) => format!(" [valid → {}]", to.format("%Y-%m-%d")),
- (None, None) => String::new(),
+ // 世界轴两端按自己的精度写(time_text);事件行上没有锚点,结束未知只能写成话
+ let range = crate::time_text::span(crate::time_text::Span {
+ valid_from: c.valid_from,
+ from_precision: c.valid_from_precision.as_deref(),
+ valid_to: c.valid_to,
+ to_precision: c.valid_to_precision.as_deref(),
+ holds_from: None,
+ holds_to: None,
+ });
+ let range = if range.is_empty() {
+ range
+ } else {
+ format!(" [valid {range}]")
};
// 文件名不带 [n]:引证编号是 chunk 的,这里只有 document,发一个编号出去
// 会在界面上落成一条指不到东西的引证
@@ -944,6 +992,36 @@ mod tests {
// --- change_line --------------------------------------------------------
+ /// 年精度的起点写成年,不再印成 1 月 1 日;结束了不知哪天绝不写 now
+ #[test]
+ fn a_change_line_shows_each_end_at_its_precision() {
+ let mut c = change("asserted");
+ c.valid_from = Some(t("2019-01-01T00:00:00Z"));
+ c.valid_from_precision = Some("year".into());
+ assert!(
+ change_line(&c).contains("[valid 2019 → now]"),
+ "{}",
+ change_line(&c)
+ );
+ c.valid_to_precision = Some("unknown".into());
+ assert!(
+ change_line(&c).contains("[valid 2019 → ended, date unknown]"),
+ "{}",
+ change_line(&c)
+ );
+ }
+
+ #[test]
+ fn a_window_end_covers_the_whole_period_named() {
+ assert_eq!(period_last_day(d("2023-01-01"), "year"), d("2023-12-31"));
+ assert_eq!(period_last_day(d("2024-02-01"), "month"), d("2024-02-29"));
+ assert_eq!(period_last_day(d("2023-12-01"), "month"), d("2023-12-31"));
+ assert_eq!(period_last_day(d("2023-06-15"), "day"), d("2023-06-15"));
+ // parse_when 与 at 同一种写法
+ assert_eq!(parse_when("2023"), Some(t("2023-01-01T00:00:00Z")));
+ assert_eq!(parse_when("2023-06"), Some(t("2023-06-01T00:00:00Z")));
+ }
+
fn change(kind: &str) -> GraphChange {
GraphChange {
fact_id: Uuid::nil(),
@@ -991,13 +1069,16 @@ mod tests {
let as_of = Some(t("2026-09-05T02:43:53.382001Z"));
assert_eq!(
entity_facts_detail(2, at, as_of),
- "2 facts at 2024-08-01, as recorded by 2026-09-05T02:43:53.382001Z"
+ "2 facts at 2024-08-01T00:00:00Z, as recorded by 2026-09-05T02:43:53.382001Z"
);
assert_eq!(
entity_facts_detail(2, None, as_of),
"2 facts as recorded by 2026-09-05T02:43:53.382001Z"
);
- assert_eq!(entity_facts_detail(2, at, None), "2 facts as of 2024-08-01");
+ assert_eq!(
+ entity_facts_detail(2, at, None),
+ "2 facts as of 2024-08-01T00:00:00Z"
+ );
assert_eq!(entity_facts_detail(0, None, None), "0 facts");
}
@@ -1076,6 +1157,7 @@ mod tests {
c.object_name = Some("Berlin".to_string());
c.predicate_label = Some("headquartered in".to_string());
c.valid_from = Some(t("2019-01-01T00:00:00Z"));
+ c.valid_from_precision = Some("day".into());
let line = change_line(&c);
assert!(
line.starts_with("2026-08-28T10:00:00Z corrected: "),
diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rs
index bd8cbbad..8bbf2578 100644
--- a/crates/utopia-server/src/main.rs
+++ b/crates/utopia-server/src/main.rs
@@ -28,6 +28,7 @@ mod rdf;
mod retrieval;
mod rss_full_content;
mod state;
+mod time_text;
mod type_resolution;
mod webdav;
diff --git a/crates/utopia-server/src/time_text.rs b/crates/utopia-server/src/time_text.rs
new file mode 100644
index 00000000..0e1335fb
--- /dev/null
+++ b/crates/utopia-server/src/time_text.rs
@@ -0,0 +1,143 @@
+//! 时间给模型看的写法:**一条规则,所有工具行都走它**。
+//!
+//! - 世界轴的端点按**自己的精度**写:year → `2023`,month → `2023-06`,day → `2023-06-01`。
+//! 从前一律 `%Y-%m-%d`——年精度的事实印成 1 月 1 日,正是 `facts.valid_from_precision`
+//! 那条注释说的病:在无知的地方填一个确定的值。多少精度写多少位。
+//! - 没有精度的时刻——`at`、`as_of`、`recorded_at`、`doc_time`,以及锚点顶上来的界
+//! (派生行的两端、没起点的事实读出来的起点,0022)——写完整 RFC3339,含小数秒。
+//! 记录轴上同一秒内可以先录入再更正(#351),截到天或秒都会把两次认知叠回一起。
+//! - 「结束了,不知哪天」写成 `ended by <锚点>`,绝不写 `now`。
+//!
+//! 界面的 `web/src/time.ts::fmtTime` 与导出的 `rdf::world_time` 是同一条规则的另两份;
+//! 三处分叉的话,人看到的、模型看到的、审计者拿到的就不是同一个日期。
+use chrono::{DateTime, SecondsFormat, Utc};
+
+/// 一个时刻,完整写出。
+pub fn instant(t: DateTime<Utc>) -> String {
+ t.to_rfc3339_opts(SecondsFormat::AutoSi, true)
+}
+
+/// 世界轴的一端,按精度写。没有精度就是一个时刻(锚点、派生的界),写完整。
+pub fn world(t: DateTime<Utc>, precision: Option<&str>) -> String {
+ match precision {
+ Some("year") => t.format("%Y").to_string(),
+ Some("month") => t.format("%Y-%m").to_string(),
+ Some("day") => t.format("%Y-%m-%d").to_string(),
+ _ => instant(t),
+ }
+}
+
+/// 一条事实的两端:原文说的(`valid_*` 与精度)和读出来的(`holds_*`,0022)。
+#[derive(Debug, Clone, Copy, Default)]
+pub struct Span<'a> {
+ pub valid_from: Option<DateTime<Utc>>,
+ pub from_precision: Option<&'a str>,
+ pub valid_to: Option<DateTime<Utc>>,
+ pub to_precision: Option<&'a str>,
+ pub holds_from: Option<DateTime<Utc>>,
+ pub holds_to: Option<DateTime<Utc>>,
+}
+
+/// `from → to`,给模型看。
+///
+/// 起点:原文给了按精度写;没给但有锚点写 `attested <时刻>`——模型该知道这条事实
+/// 只是从那份证据起有据可查。终点:原文给了按精度写;结束了不知哪天写
+/// `ended by <锚点>`(没有锚点时写 `ended, date unknown`);否则 `now`。
+/// 两端都无可写时返回空串,调用方据此决定不带括号。
+pub fn span(s: Span<'_>) -> String {
+ let from = match (s.valid_from, s.holds_from) {
+ (Some(t), _) => Some(world(t, s.from_precision)),
+ (None, Some(a)) => Some(format!("attested {}", instant(a))),
+ (None, None) => None,
+ };
+ let ended_unknown =
+ s.valid_to.is_none() && s.to_precision == Some(utopia_store::graph::ENDED_UNKNOWN);
+ let to = match (s.valid_to, ended_unknown, s.holds_to) {
+ (Some(t), _, _) => Some(world(t, s.to_precision)),
+ (None, true, Some(a)) => Some(format!("ended by {}", instant(a))),
+ (None, true, None) => Some("ended, date unknown".to_string()),
+ (None, false, _) => None,
+ };
+ match (from, to) {
+ (None, None) => String::new(),
+ (Some(f), None) => format!("{f} → now"),
+ (None, Some(t)) => format!("→ {t}"),
+ (Some(f), Some(t)) => format!("{f} → {t}"),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn t(s: &str) -> DateTime<Utc> {
+ s.parse().unwrap()
+ }
+
+ #[test]
+ fn a_world_bound_shows_exactly_its_precision() {
+ let at = t("2023-06-15T00:00:00Z");
+ assert_eq!(world(at, Some("year")), "2023");
+ assert_eq!(world(at, Some("month")), "2023-06");
+ assert_eq!(world(at, Some("day")), "2023-06-15");
+ // 没有精度 = 一个时刻(锚点、派生的界):写完整,不冒充哪一天
+ assert_eq!(world(at, None), "2023-06-15T00:00:00Z");
+ }
+
+ #[test]
+ fn an_instant_keeps_its_fraction_and_reads_back() {
+ for s in [
+ "2026-09-05T02:43:53Z",
+ "2026-09-05T02:43:53.382Z",
+ "2026-09-05T02:43:53.382001Z",
+ ] {
+ assert_eq!(instant(t(s)), s);
+ }
+ }
+
+ #[test]
+ fn a_span_reads_each_end_by_its_own_rule() {
+ let day = |s: &str| Some(t(s));
+ // 原文给了两端
+ assert_eq!(
+ span(Span {
+ valid_from: day("2023-01-01T00:00:00Z"),
+ from_precision: Some("year"),
+ valid_to: day("2024-07-01T00:00:00Z"),
+ to_precision: Some("month"),
+ holds_from: day("2023-01-01T00:00:00Z"),
+ holds_to: day("2024-07-01T00:00:00Z"),
+ }),
+ "2023 → 2024-07"
+ );
+ // 没起点:从证据起;仍在继续
+ assert_eq!(
+ span(Span {
+ holds_from: day("2024-02-20T00:00:00Z"),
+ ..Span::default()
+ }),
+ "attested 2024-02-20T00:00:00Z → now"
+ );
+ // 结束了不知哪天:到说出它的那份文档为止,绝不是 now
+ assert_eq!(
+ span(Span {
+ valid_from: day("2023-06-01T00:00:00Z"),
+ from_precision: Some("day"),
+ valid_to: None,
+ to_precision: Some("unknown"),
+ holds_from: day("2023-06-01T00:00:00Z"),
+ holds_to: day("2025-10-15T00:00:00Z"),
+ }),
+ "2023-06-01 → ended by 2025-10-15T00:00:00Z"
+ );
+ // 记录轴事件里没有锚点可用
+ assert_eq!(
+ span(Span {
+ to_precision: Some("unknown"),
+ ..Span::default()
+ }),
+ "→ ended, date unknown"
+ );
+ assert_eq!(span(Span::default()), "");
+ }
+}
diff --git a/crates/utopia-store/src/temporal.rs b/crates/utopia-store/src/temporal.rs
index 773913b2..0a936bac 100644
--- a/crates/utopia-store/src/temporal.rs
+++ b/crates/utopia-store/src/temporal.rs
@@ -536,15 +536,19 @@ pub async fn list_conflicts(
/// 人工裁决:close(旧事实闭合于 close_at 或新事实起点)/ keep(并存不矛盾)/
/// reject_new(新事实是抽取错误,作废)。
+/// 一条待裁决的冲突:旧事实、新事实、新事实的起点及其精度
+type ConflictRow = (Uuid, Uuid, Option<DateTime<Utc>>, Option<String>);
+
pub async fn resolve_conflict(
pool: &PgPool,
kb_id: Uuid,
conflict_id: Uuid,
resolution: &str,
close_at: Option<DateTime<Utc>>,
+ close_at_precision: &str,
) -> AppResult<()> {
- let row: Option<(Uuid, Uuid, Option<DateTime<Utc>>)> = sqlx::query_as(
- "SELECT c.old_fact_id, c.new_fact_id, fn_.valid_from
+ let row: Option<ConflictRow> = sqlx::query_as(
+ "SELECT c.old_fact_id, c.new_fact_id, fn_.valid_from, fn_.valid_from_precision
FROM fact_conflicts c JOIN facts fn_ ON fn_.id = c.new_fact_id
WHERE c.id = $1 AND c.kb_id = $2 AND c.status = 'open'",
)
@@ -552,19 +556,28 @@ pub async fn resolve_conflict(
.bind(kb_id)
.fetch_optional(pool)
.await?;
- let Some((old_fact_id, new_fact_id, new_from)) = row else {
+ let Some((old_fact_id, new_fact_id, new_from, new_from_precision)) = row else {
return Err(utopia_core::AppError::NotFound);
};
let stored = match resolution {
"close" => {
- let at = close_at.or(new_from).ok_or_else(|| {
- utopia_core::AppError::invalid(
- "close_at_required",
- "close_at is required when the new fact has no start time",
- )
- })?;
- close_superseded(pool, old_fact_id, at, "day").await?;
+ // 闭合点带着它的精度走:人给了日期就用人给的精度,没给就闭合在新事实的
+ // 起点——那个起点是几月还是几号,闭合点就是几月还是几号。从前一律写 day,
+ // 「2023 年 6 月接任」把前任闭合成了 6 月 1 日
+ let (at, precision) = match close_at {
+ Some(at) => (at, close_at_precision),
+ None => (
+ new_from.ok_or_else(|| {
+ utopia_core::AppError::invalid(
+ "close_at_required",
+ "close_at is required when the new fact has no start time",
+ )
+ })?,
+ new_from_precision.as_deref().unwrap_or("day"),
+ ),
+ };
+ close_superseded(pool, old_fact_id, at, precision).await?;
"closed"
}
"keep" => "kept_both",
diff --git a/web/src/api.ts b/web/src/api.ts
index ca96f6a0..599c98a1 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -1943,15 +1943,20 @@ export const api = {
}>(
`/api/v1/kbs/${kbId}/review?queue=${queue}&limit=${limit}&offset=${offset}`,
),
- closeFact: (kbId: string, factId: string, validTo: string) =>
+ /** 闭合日期带精度(year | month | day):写多少位就是多少精度,服务端照存 */
+ closeFact: (kbId: string, factId: string, validTo: string, precision: string) =>
request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/close`, {
method: "POST",
- body: JSON.stringify({ valid_to: validTo }),
+ body: JSON.stringify({ valid_to: validTo, valid_to_precision: precision }),
}),
resolveConflict: (
kbId: string,
conflictId: string,
- body: { action: "close" | "keep" | "reject_new"; close_at?: string },
+ body: {
+ action: "close" | "keep" | "reject_new";
+ close_at?: string;
+ close_at_precision?: string;
+ },
) =>
request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conflicts/${conflictId}`, {
method: "POST",
@@ -2062,7 +2067,7 @@ export const api = {
kbId: string,
violationId: string,
resolution: ViolationResolution,
- opts: { closeAt?: string; factId?: string } = {},
+ opts: { closeAt?: string; closeAtPrecision?: string; factId?: string } = {},
) =>
request<{ ok: boolean }>(
`/api/v1/kbs/${kbId}/review/violations/${violationId}`,
@@ -2071,6 +2076,7 @@ export const api = {
body: JSON.stringify({
resolution,
close_at: opts.closeAt ?? null,
+ close_at_precision: opts.closeAtPrecision ?? null,
fact_id: opts.factId ?? null,
}),
},
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 6ce71575..ffef3a7a 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -1687,7 +1687,7 @@ export const en = {
closeOldAt: (d: string) => `Close old at ${d}`,
keepBoth: "Keep both",
rejectNew: "Reject new",
- closeAtPlaceholder: "YYYY-MM-DD",
+ closeAtPlaceholder: "YYYY-MM-DD · YYYY-MM · YYYY",
unconfirmed: "No longer stated",
unconfirmedHint:
"Every source that stated these facts has since been updated without them. " +
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 57f1b594..8220f47b 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -1475,7 +1475,7 @@ export const zh: Strings = {
closeOldAt: (d: string) => `在 ${d} 闭合旧的`,
keepBoth: "两条都留",
rejectNew: "驳回新的",
- closeAtPlaceholder: "YYYY-MM-DD",
+ closeAtPlaceholder: "YYYY-MM-DD · YYYY-MM · YYYY",
unconfirmed: "已不再被陈述",
unconfirmedHint:
"曾经陈述这些事实的每一个来源,此后都更新过且不再包含它们。" +
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
index 2437d3d6..16f01524 100644
--- a/web/src/pages/Graph.tsx
+++ b/web/src/pages/Graph.tsx
@@ -34,6 +34,7 @@ import {
TRANSPARENT,
} from "./graphVisuals";
import { EntityHistory } from "./EntityHistory";
+import { fmtTime, parseDateInput } from "../time";
import { NextStep, nextStep, useReadiness } from "./NextStep";
import {
ArrowLeft,
@@ -2103,44 +2104,6 @@ function TimeScrubber({
/* ============ 实体侧栏 ============ */
-/** 世界时间(这件事何时成立)→ 文本。**一律按 UTC 读,不转本地。**
- *
- * `valid_from` / `valid_to` 来自文档里的陈述("2019 年 5 月 2 日就任"),
- * 是**日历日期不是时刻**,本来就没有时区;存的是那一天的 UTC 午夜。
- * 按本地渲染会让 UTC-5 的读者看到 2019-05-01——凭空差一天,而且差的方向
- * 还随读者所在地变。记录时间(我们何时这么认为)是另一回事,那个该按本地,
- * 见 EntityHistory 里 ymd 的注释。 */
-function fmtTime(iso: string | null, precision: string | null): string | null {
- if (!iso) return null;
- const d = new Date(iso);
- const y = d.getUTCFullYear();
- const m = String(d.getUTCMonth() + 1).padStart(2, "0");
- const day = String(d.getUTCDate()).padStart(2, "0");
- if (precision === "year") return `${y}`;
- if (precision === "month") return `${y}-${m}`;
- return `${y}-${m}-${day}`;
-}
-
-/** 输入框里的日期 → 时间戳 + 精度。**写多少位就是多少精度**,与抽取端
- * `parse_time` 同一个约定:2023 是「那一年」,2023-06 是「那个月」。
- *
- * 这也是不用日期选择器的理由——选择器逼人给出一个日,而「文档只说了上半年」
- * 正是这个表单要修的那种错。回读比对是因为 `new Date("2023-13")` 不报错。 */
-function parseDateInput(
- s: string,
-): { iso: string; precision: string } | null {
- const t = s.trim();
- const shape = /^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/.exec(t);
- if (!shape) return null;
- const [, y, m, d] = shape;
- const iso = `${y}-${m ?? "01"}-${d ?? "01"}T00:00:00.000Z`;
- const parsed = new Date(iso);
- if (Number.isNaN(parsed.getTime())) return null;
- // 溢出静默:2023-13-01 会变成 2024-01-01,2023-02-30 会变成 3 月
- if (parsed.toISOString().slice(0, 10) !== iso.slice(0, 10)) return null;
- return { iso, precision: d ? "day" : m ? "month" : "year" };
-}
-
function fmtInterval(f: EntityFact): string {
if (f.temporal === "eternal") return "";
const from = fmtTime(f.valid_from, f.valid_from_precision);
diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsx
index 9777cad9..d88f0f85 100644
--- a/web/src/pages/Review.tsx
+++ b/web/src/pages/Review.tsx
@@ -16,6 +16,7 @@ import {
type ReviewSide,
type ViolationResolution,
} from "../api";
+import { parseDateInput } from "../time";
import { PendingFactRow, useCanDecide } from "./PendingFacts";
import { ReviewOverview } from "./ReviewOverview";
import { S } from "../i18n";
@@ -214,15 +215,15 @@ function ConflictRow({
onResolve: (
action: "close" | "keep" | "reject_new",
closeAt?: string,
+ closeAtPrecision?: string,
) => void;
}) {
const [closeAt, setCloseAt] = useState("");
const c = conflict;
const needsDate = !c.new_valid_from;
- // close_at 输入按天精度转 RFC3339
- const closeAtIso = /^\d{4}-\d{2}-\d{2}$/.test(closeAt.trim())
- ? `${closeAt.trim()}T00:00:00Z`
- : undefined;
+ // 写多少位就是多少精度(time.ts):「2023-06」闭合在那个月,不编一个 1 日
+ const closeParsed = parseDateInput(closeAt);
+ const closeAtIso = closeParsed?.iso;
return (
<div className="glass rounded-xl p-4">
@@ -278,7 +279,7 @@ function ConflictRow({
)}
<Button variant="secondary" size="sm"
disabled={busy || (needsDate && !closeAtIso)}
- onClick={() => onResolve("close", closeAtIso)}
+ onClick={() => onResolve("close", closeAtIso, closeParsed?.precision)}
>
{c.new_valid_from
? S.review.closeOldAt(c.new_valid_from.slice(0, 10))
@@ -299,12 +300,11 @@ function UnconfirmedRow({
fact: FactReviewItem;
busy: boolean;
onReject: () => void;
- onClose: (validTo: string) => void;
+ onClose: (validTo: string, precision: string) => void;
}) {
const [closeAt, setCloseAt] = useState("");
- const closeAtIso = /^\d{4}-\d{2}-\d{2}$/.test(closeAt.trim())
- ? `${closeAt.trim()}T00:00:00Z`
- : undefined;
+ const closeParsed = parseDateInput(closeAt);
+ const closeAtIso = closeParsed?.iso;
const range = dateRange(fact.valid_from, fact.valid_to);
return (
@@ -352,7 +352,9 @@ function UnconfirmedRow({
/>
<Button variant="secondary" size="sm"
disabled={busy || !closeAtIso}
- onClick={() => closeAtIso && onClose(closeAtIso)}
+ onClick={() =>
+ closeParsed && onClose(closeParsed.iso, closeParsed.precision)
+ }
>
{closeAt.trim()
? S.review.closeFactAt(closeAt.trim())
@@ -549,7 +551,7 @@ function DefectRow({
* 矛盾可能出在定义上(用户导的本体把某个属性声明成反对称,而他的语料里
* 那关系其实双向),这时该改的是本体,不是二十条事实。 */
/** 裁决的附加参数:闭合日期(fact_closed)、撤哪条(fact_retracted) */
-type DecideOpts = { closeAt?: string; factId?: string };
+type DecideOpts = { closeAt?: string; closeAtPrecision?: string; factId?: string };
function ViolationRow({
violation: v,
@@ -698,17 +700,25 @@ function ContradictionRow({
</div>
<p className="mt-2 text-small text-ink-3">{hint}</p>
<div className="mt-2 flex gap-2 flex-wrap items-center">
- <Input size="sm" className="u-num"
- type="date"
+ {/* 不用日期选择器:它逼人给出一个日,而「那年结束的」正是这里常见的答案。
+ 写多少位就是多少精度(time.ts) */}
+ <Input size="sm" className="u-num w-28 text-center"
+ placeholder={S.review.closeAtPlaceholder}
value={closeAt}
title={S.review.closeAssertion}
onChange={(e) => setCloseAt(e.target.value)}
/>
<Button variant="primary" size="sm"
- disabled={busy || !closeAt}
- onClick={() =>
- onDecide("fact_closed", { closeAt: new Date(closeAt).toISOString() })
- }
+ disabled={busy || !parseDateInput(closeAt)}
+ onClick={() => {
+ const parsed = parseDateInput(closeAt);
+ if (parsed) {
+ onDecide("fact_closed", {
+ closeAt: parsed.iso,
+ closeAtPrecision: parsed.precision,
+ });
+ }
+ }}
>
{S.review.closeAssertion}
</Button>
@@ -935,17 +945,31 @@ export function Review() {
id,
action,
closeAt,
+ closeAtPrecision,
}: {
id: string;
action: "close" | "keep" | "reject_new";
closeAt?: string;
- }) => api.resolveConflict(kb!.id, id, { action, close_at: closeAt }),
+ closeAtPrecision?: string;
+ }) =>
+ api.resolveConflict(kb!.id, id, {
+ action,
+ close_at: closeAt,
+ close_at_precision: closeAtPrecision,
+ }),
onSettled: invalidate,
});
const closeFactAction = useMutation({
- mutationFn: ({ id, validTo }: { id: string; validTo: string }) =>
- api.closeFact(kb!.id, id, validTo),
+ mutationFn: ({
+ id,
+ validTo,
+ precision,
+ }: {
+ id: string;
+ validTo: string;
+ precision: string;
+ }) => api.closeFact(kb!.id, id, validTo, precision),
onSettled: invalidate,
});
@@ -1188,8 +1212,13 @@ export function Review() {
conflictAction.isPending &&
conflictAction.variables?.id === c.id
}
- onResolve={(action, closeAt) =>
- conflictAction.mutate({ id: c.id, action, closeAt })
+ onResolve={(action, closeAt, closeAtPrecision) =>
+ conflictAction.mutate({
+ id: c.id,
+ action,
+ closeAt,
+ closeAtPrecision,
+ })
}
/>
))}
@@ -1211,8 +1240,8 @@ export function Review() {
onReject={() =>
factAction.mutate({ id: fact.id, action: "reject" })
}
- onClose={(validTo) =>
- closeFactAction.mutate({ id: fact.id, validTo })
+ onClose={(validTo, precision) =>
+ closeFactAction.mutate({ id: fact.id, validTo, precision })
}
/>
))}
diff --git a/web/src/time.ts b/web/src/time.ts
new file mode 100644
index 00000000..46d40d09
--- /dev/null
+++ b/web/src/time.ts
@@ -0,0 +1,47 @@
+/** 世界轴日期的读与写,一条规则,全站共用。
+ *
+ * 服务端的 `time_text`(给模型看的)与导出的 `rdf::world_time`(给审计者的)是同一条
+ * 规则的另两份;三处分叉,人看到的、模型看到的、审计者拿到的就不是同一个日期。 */
+
+/** 世界轴的一端按**自己的精度**显示:year → 2023,month → 2023-06,day → 2023-06-01。
+ * 多少精度显示多少位——从前一律到日,年精度的事实显示成 1 月 1 日,是在无知的
+ * 地方填一个确定的值。没有精度的日期(派生行上来自证据的界,0022)按日显示。
+ *
+ * 按 UTC 取年月日而不是本地:`valid_from` / `valid_to` 来自文档里的陈述
+ * ("2019 年 5 月 2 日就任"),是**日历日期不是时刻**,本来就没有时区;存的是那一天
+ * 的 UTC 午夜。按本地渲染会让 UTC-5 的读者看到 2019-05-01——凭空差一天,而且差的
+ * 方向还随读者所在地变。记录时间(我们何时这么认为)是另一回事,那个该按本地,
+ * 见 EntityHistory 里 ymd 的注释。 */
+export function fmtTime(
+ iso: string | null,
+ precision: string | null,
+): string | null {
+ if (!iso) return null;
+ const d = new Date(iso);
+ const y = d.getUTCFullYear();
+ const m = String(d.getUTCMonth() + 1).padStart(2, "0");
+ const day = String(d.getUTCDate()).padStart(2, "0");
+ if (precision === "year") return `${y}`;
+ if (precision === "month") return `${y}-${m}`;
+ return `${y}-${m}-${day}`;
+}
+
+/** 输入框里的日期 → 时间戳 + 精度。**写多少位就是多少精度**,与抽取端
+ * `parse_time` 同一个约定:2023 是「那一年」,2023-06 是「那个月」。
+ *
+ * 这也是不用日期选择器的理由——选择器逼人给出一个日,而「文档只说了上半年」
+ * 正是这个表单要修的那种错。回读比对是因为 `new Date("2023-13")` 不报错。 */
+export function parseDateInput(
+ s: string,
+): { iso: string; precision: string } | null {
+ const t = s.trim();
+ const shape = /^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/.exec(t);
+ if (!shape) return null;
+ const [, y, m, d] = shape;
+ const iso = `${y}-${m ?? "01"}-${d ?? "01"}T00:00:00.000Z`;
+ const parsed = new Date(iso);
+ if (Number.isNaN(parsed.getTime())) return null;
+ // 溢出静默:2023-13-01 会变成 2024-01-01,2023-02-30 会变成 3 月
+ if (parsed.toISOString().slice(0, 10) !== iso.slice(0, 10)) return null;
+ return { iso, precision: d ? "day" : m ? "month" : "year" };
+}