Skip to content

World's first open-source enterprise world model.

A date the text spells out is read as a date (#689)

WaylandYang0306d0cf70b5
diff --git a/crates/utopia-extract/src/lib.rs b/crates/utopia-extract/src/lib.rs
index 6e1ca4c8..713bd86c 100644
--- a/crates/utopia-extract/src/lib.rs
+++ b/crates/utopia-extract/src/lib.rs
@@ -295,7 +295,7 @@ pub fn build_messages_with_opening(
let attr_rules = if attributes.is_empty() {
String::new()
} else {
- "\n10. Attribute facts carry \"value\" (no \"object\"): number = the figure **as the text writes it, magnitude and currency included** \n (\"86亿元\", \"$5 billion\", \"4,300 人\") — never reduce it to a bare number, the server converts; date = \"YYYY[-MM[-DD]]\" (a zoned clock time only when the text gives one) — a date the text gives only relative to an event \
+ "\n11. Attribute facts carry \"value\" (no \"object\"): number = the figure **as the text writes it, magnitude and currency included** \n (\"86亿元\", \"$5 billion\", \"4,300 人\") — never reduce it to a bare number, the server converts; date = \"YYYY[-MM[-DD]]\" (a zoned clock time only when the text gives one) — a date the text gives only relative to an event \
(\"45 days after the Trigger Date\", \"within 30 days of closing\") has no calendar date to convert: write it as the text writes it and add \"relative\": true; bool = true/false; \
text = a short string. Only attach an attribute to a subject of its listed class. \
valid_from = when this value took effect, if the text or the opening of the document says so. \
@@ -380,15 +380,14 @@ pub fn build_messages_with_opening(
fits — \"purchase_price\", \"job_title\", \"generation_capacity\", \"record_date\". \
Attach it to the entity the text attaches it to, and keep the literal as written, \
units and all — except a date, which is always written in the format of rule 3 \
- (\"June 23, 2020\" is \"2020-06-23\"): the server keeps a date only in that \
- format, and a date written any other way is lost. A deadline or a period stated \
+ (\"June 23, 2020\" is \"2020-06-23\"). A deadline or a period stated \
relative to an event, with no calendar date, is not a date: keep it as written \
- and mark it \"relative\" as rule 10 says. \
+ and mark it \"relative\" as rule 11 says. \
**A stated figure left out is the loss that costs most**: the reader \
came for those numbers, and no later step can recover one that was never written \
down.\n\
- 8c. A listed relation followed by {{…}} can carry those **qualifiers on the edge**: when the same sentence gives both the other entity and a figure for it — an amount, a stake, a price, a share count — write the relation with its \"object\" and put the figure in \"qualifiers\" keyed exactly as listed, **as written in the text, currency and all** (\"€30 million\", \"15亿元人民币\", never a bare number) — except a date, which takes the format of rule 3: {{\"subject\":\"Vega Capital\",\"predicate\":\"invested_in\",\"object\":\"Northwind\", \"qualifiers\":{{\"amount\":\"$5 billion\"}},…}}. Never invent a key that is not listed for that relation, and never drop the figure to keep the edge — a relation without its amount is half the sentence. A relation you name after the text (rule 8) carries its figure the same way — keyed by the listed attribute that fits it, or by the plainest word for it (\"amount\", \"stake\", \"price\") when none does.
- 8b. A **listed** relation also takes \"value\" when what the text gives is a \
+ 8b. A listed relation followed by {{…}} can carry those **qualifiers on the edge**: when the same sentence gives both the other entity and a figure for it — an amount, a stake, a price, a share count — write the relation with its \"object\" and put the figure in \"qualifiers\" keyed exactly as listed, **as written in the text, currency and all** (\"€30 million\", \"15亿元人民币\", never a bare number) — except a date, which takes the format of rule 3: {{\"subject\":\"Vega Capital\",\"predicate\":\"invested_in\",\"object\":\"Northwind\", \"qualifiers\":{{\"amount\":\"$5 billion\"}},…}}. Never invent a key that is not listed for that relation, and never drop the figure to keep the edge — a relation without its amount is half the sentence. A relation you name after the text (rule 8) carries its figure the same way — keyed by the listed attribute that fits it, or by the plainest word for it (\"amount\", \"stake\", \"price\") when none does.
+ 8c. A **listed** relation also takes \"value\" when what the text gives is a \
string rather than another entity — a job title, a designation, a ticker, a \
model number. Never invent an entity for a string. And when the text introduces \
someone by their role — \"X, founder and CEO of Y\", \"Z, co-CEO of W\", \
@@ -402,15 +401,15 @@ pub fn build_messages_with_opening(
(\"appointed … as OpenAI's CTO of applications\") all carry the same \
shape — the role is the value, the organization is the other \
entity. Past tense and \"former\" give the tie valid_to: \"unknown\".\n\
- 8c. A list of named parties is a list of facts — one per name. \"partners \
+ 8d. A list of named parties is a list of facts — one per name. \"partners \
including A, B, C and D\" is four facts, not one; \"advisors A and B\" is two. \
Do not collapse an enumeration into a summary or into its first member. \
The same applies to the entities: each named party is its own entity.\n\
- 8d. subject_span and object_span are the exact words in quote that name each side. \
+ 8e. subject_span and object_span are the exact words in quote that name each side. \
Copy them; never paraphrase. When the words that do the thing are a description \
rather than a name — \"former X employees\", \"companies using X\" — the span \
is that description, whatever you wrote in subject.\n\
- 8e. An obligation, a deadline or a right belongs to the agreement, law or decision \
+ 8f. An obligation, a deadline or a right belongs to the agreement, law or decision \
that imposes it, even when it concerns another agreement or thing. A lease that \
sets the last day to sign a second lease gives that deadline to the first lease; \
the second lease is only what the deadline is about.\n\
@@ -1071,7 +1070,8 @@ pub fn attr_object_value(
}
/// 属性值按 datatype 归一。失败返回 None——宁缺勿脏,调用方跳过并记日志。
-/// number 容忍千分位/空格;date 要求 YYYY[-MM[-DD]] 且保留原精度;bool 宽容 yes/no。
+/// number 容忍千分位/空格;date 收规则 3 的格式(YYYY[-MM[-DD]]、带时区的时刻,原样保留),
+/// 也收写法说得清是哪天的日期([`written_date`]),换成规则 3 的样子;bool 宽容 yes/no。
pub fn normalize_attr_value(datatype: &str, raw: &serde_json::Value) -> Option<serde_json::Value> {
match datatype {
"number" => match raw {
@@ -1104,9 +1104,17 @@ pub fn normalize_attr_value(datatype: &str, raw: &serde_json::Value) -> Option<s
}
_ => None,
},
+ // 按规则 3 写的原样留着(精度随写了几位,带时区的时刻也在内);写成别的样子、又读得
+ // 出来的日期(#688)换成规则 3 的样子——同一天只该有一种写法,比较和去重才对得上
"date" => {
let s = raw.as_str()?.trim();
- parse_time(s).map(|_| serde_json::Value::String(s.to_string()))
+ match written_date(s) {
+ Some((date, precision)) => Some(serde_json::Value::String(match precision {
+ "month" => date.format("%Y-%m").to_string(),
+ _ => date.format("%Y-%m-%d").to_string(),
+ })),
+ None => parse_time(s).map(|_| serde_json::Value::String(s.to_string())),
+ }
}
"bool" => match raw {
serde_json::Value::Bool(b) => Some(serde_json::Value::Bool(*b)),
@@ -1134,6 +1142,8 @@ pub fn normalize_attr_value(datatype: &str, raw: &serde_json::Value) -> Option<s
/// `YYYY-MM-DDTHH[:MM[:SS]]` 后跟 `Z` 或 `±HH:MM`,精度到 hour / minute / second,
/// 值截到那一位。**没有时区的钟点不是时刻**——「14:32」是哪里的 14:32 没人知道——
/// 所以只取日期那一半,按天;钟点留在引文里。亚秒一律丢:账本到秒为止。
+///
+/// 这是规则 3 的契约格式,工具参数、界面上的时刻都只认它。读模型回复用 [`read_time`]
pub fn parse_time(s: &str) -> Option<(DateTime<Utc>, &'static str)> {
let s = s.trim();
if s.is_empty() || s.eq_ignore_ascii_case("null") {
@@ -1171,6 +1181,94 @@ pub fn parse_time(s: &str) -> Option<(DateTime<Utc>, &'static str)> {
None
}
+/// 读模型回复里的时间:先按规则 3([`parse_time`]);没照它写、但写法说得清是哪天的日期
+/// 也收([`written_date`],#688)。区间端点、日期属性、边上的日期属性都从这里读
+pub fn read_time(s: &str) -> Option<(DateTime<Utc>, &'static str)> {
+ parse_time(s).or_else(|| {
+ let (date, precision) = written_date(s)?;
+ Some((
+ Utc.from_utc_datetime(&date.and_hms_opt(0, 0, 0)?),
+ precision,
+ ))
+ })
+}
+
+/// 没照规则 3 写、但说得清是哪一天(或哪个月)的日期(#688)。
+///
+/// 合同、公告里的日期多半这么写,模型常常照抄;从前这些值全被当成「不是日期」丢掉。
+/// 收两类,精度随写了几位——只写到月的就是月,不替它补一个日:
+/// - 月份写成名字的:`March 17, 2020`、`17 March 2020`、`Mar. 17 2020`、`March 2020`。
+/// 名字由 chrono 的 `%B` / `%b` 认(整名或三个字母的缩写,不分大小写)
+/// - 年在前的数字:`2020/03/17`、`2020.3.17`、`2020年3月17日`、`2020年3月`
+///
+/// **日、月都是数字而年不在前的不收**:`03/04/2020` 是三月四日还是四月三日,写法本身说
+/// 不清,猜错一次就是一个错的截止日。
+pub fn written_date(s: &str) -> Option<(NaiveDate, &'static str)> {
+ let s = s.trim();
+ if let Some(found) = year_first_date(s) {
+ return found;
+ }
+ // 月份写成名字的:句点(缩写后面那个)与逗号只是标点
+ let words: Vec<&str> = s
+ .split(|c: char| c.is_whitespace() || c == ',' || c == '.')
+ .filter(|w| !w.is_empty())
+ .collect();
+ let is_number = |w: &str| w.chars().all(|c| c.is_ascii_digit());
+ let (day, month, year) = match words.as_slice() {
+ [m, d, y] if !is_number(m) && is_number(d) && is_number(y) => (Some(*d), *m, *y),
+ [d, m, y] if is_number(d) && !is_number(m) && is_number(y) => (Some(*d), *m, *y),
+ [m, y] if !is_number(m) && is_number(y) => (None, *m, *y),
+ _ => return None,
+ };
+ if year.len() != 4 || day.is_some_and(|d| d.len() > 2) {
+ return None;
+ }
+ let month = ["%B", "%b"].iter().find_map(|f| {
+ NaiveDate::parse_from_str(&format!("1 {month} 2000"), &format!("%d {f} %Y"))
+ .ok()
+ .map(|d| chrono::Datelike::month(&d))
+ })?;
+ let year = year.parse().ok()?;
+ match day {
+ Some(d) => NaiveDate::from_ymd_opt(year, month, d.parse().ok()?).map(|date| (date, "day")),
+ None => NaiveDate::from_ymd_opt(year, month, 1).map(|date| (date, "month")),
+ }
+}
+
+/// 年在前的数字日期。外层 `None` = 不是这种写法,交给下一种;`Some(None)` = 是这种写法
+/// 但不是真实的日子
+fn year_first_date(s: &str) -> Option<Option<(NaiveDate, &'static str)>> {
+ let marked = s.contains('年');
+ let separated = s.contains(['/', '.']) && !s.contains(char::is_whitespace);
+ if !marked && !separated {
+ return None;
+ }
+ let parts: Vec<&str> = s
+ .trim_end_matches('日')
+ .split(['/', '.', '年', '月'])
+ .filter(|p| !p.is_empty())
+ .collect();
+ if !parts.iter().all(|p| p.chars().all(|c| c.is_ascii_digit())) {
+ return None;
+ }
+ if parts.first().is_none_or(|y| y.len() != 4) {
+ // 年不在前:日月顺序说不清,不交给别的写法去猜
+ return Some(None);
+ }
+ let number = |p: &str| p.parse::<u32>().ok();
+ let year = parts[0].parse::<i32>().ok()?;
+ Some(match parts[1..] {
+ [m, d] if m.len() <= 2 && d.len() <= 2 => {
+ NaiveDate::from_ymd_opt(year, number(m)?, number(d)?).map(|date| (date, "day"))
+ }
+ // 只到月:写了「年」「月」才算(`2020/03` 太像别的东西)
+ [m] if marked && s.ends_with('月') && m.len() <= 2 => {
+ NaiveDate::from_ymd_opt(year, number(m)?, 1).map(|date| (date, "month"))
+ }
+ _ => None,
+ })
+}
+
/// 钟点后面的时区:`Z` 或 `±HH[:]MM` / `±HH`。返回 (钟点, 相对 UTC 的偏移);
/// 没有时区返回 None——调用方据此只记那一天
fn split_zone(clock: &str) -> Option<(&str, chrono::Duration)> {
@@ -1377,6 +1475,48 @@ mod prompt_shape_tests {
assert!(system.contains("except a date, which is always written in the format of rule 3"));
}
+ /// 规则编号各不相同,「按规则 N」指得到唯一的一条。从前有两条 8c、两条 10,
+ /// 「as rule 10 says」说的是哪条要靠猜(#689 评审)
+ #[test]
+ fn every_rule_has_its_own_number_and_every_reference_lands() {
+ let rels = vec![PromptRelation {
+ key: "acquired".into(),
+ label: "acquired".into(),
+ description: String::new(),
+ signature: String::new(),
+ temporal: "event".into(),
+ qualifiers: vec![],
+ }];
+ let attrs = vec!["lease.option_deadline (date)".to_string()];
+ let msgs = build_messages(&[], &rels, &attrs, None, "a.txt", &[], "text");
+ let system = &msgs[0].content;
+ let mut labels = Vec::new();
+ for line in system.lines() {
+ let Some((label, _)) = line.trim_start().split_once(". ") else {
+ continue;
+ };
+ let digits = label.trim_end_matches(|c: char| c.is_ascii_lowercase());
+ if !digits.is_empty()
+ && digits.chars().all(|c| c.is_ascii_digit())
+ && label.len() - digits.len() <= 1
+ {
+ labels.push(label.to_string());
+ }
+ }
+ let unique: std::collections::BTreeSet<_> = labels.iter().collect();
+ assert_eq!(unique.len(), labels.len(), "规则编号重复:{labels:?}");
+ for (i, _) in system.match_indices("rule ") {
+ let n: String = system[i + 5..]
+ .chars()
+ .take_while(|c| c.is_ascii_alphanumeric())
+ .collect();
+ assert!(
+ labels.contains(&n),
+ "「rule {n}」指不到任何一条:{labels:?}"
+ );
+ }
+ }
+
#[test]
fn a_later_chunk_reads_the_opening_of_its_document() {
let opening = "FIFTH AMENDMENT TO LEASE AGREEMENT entered into as of February 18, 2020";
@@ -1694,6 +1834,71 @@ mod tests {
assert!(parse_time("null").is_none());
assert!(parse_time("").is_none());
assert!(parse_time("下个月").is_none());
+ // 契约格式之外的写法不归它:工具参数里的「August 2024」不猜
+ assert!(parse_time("June 23, 2020").is_none());
+ // 读模型回复的那一个收写出来的日期(#688),精度随写了几位
+ let (t, p) = read_time("June 23, 2020").unwrap();
+ assert_eq!(
+ (t.to_rfc3339(), p),
+ ("2020-06-23T00:00:00+00:00".to_string(), "day")
+ );
+ assert_eq!(read_time("March 2020").unwrap().1, "month");
+ assert_eq!(read_time("2024-07").unwrap().1, "month");
+ assert!(read_time("03/04/2020").is_none());
+ }
+
+ /// 合同与公告里的日期写法(#688):说得清是哪天的都收成规则 3 的样子,说不清的不猜
+ #[test]
+ fn a_written_date_is_read_only_when_its_form_says_which_day() {
+ use serde_json::json;
+ let day = |s: &str| normalize_attr_value("date", &json!(s));
+ for written in [
+ "March 17, 2020",
+ "March 17 2020",
+ "march 17, 2020",
+ "MARCH 17, 2020",
+ "Mar 17, 2020",
+ "Mar. 17, 2020",
+ "17 March 2020",
+ "17 Mar. 2020",
+ "17 March, 2020",
+ " March 17, 2020 ",
+ "2020/03/17",
+ "2020.3.17",
+ "2020年3月17日",
+ ] {
+ assert_eq!(day(written), Some(json!("2020-03-17")), "{written}");
+ }
+ // 只写到月的是月,不补日
+ for written in ["March 2020", "Mar. 2020", "2020年3月"] {
+ assert_eq!(day(written), Some(json!("2020-03")), "{written}");
+ }
+ // 已经照规则 3 写的原样留着
+ assert_eq!(day("2020-03-17"), Some(json!("2020-03-17")));
+ assert_eq!(day("2020"), Some(json!("2020")));
+ // 日月都是数字、年不在前:说不清是几月几号
+ for ambiguous in ["03/04/2020", "3.4.2020", "04-03-2020", "3/4/20"] {
+ assert_eq!(day(ambiguous), None, "{ambiguous}");
+ }
+ // 不是日期,或不是一个真实的日子
+ for not_a_date in [
+ "45 days after the Trigger Date",
+ "Q3 2020",
+ "Sometime 2020",
+ "February 30, 2020",
+ "March 17, 20",
+ "March 123, 2020",
+ "2020/13/01",
+ "2020/03",
+ "next March",
+ ] {
+ assert_eq!(day(not_a_date), None, "{not_a_date}");
+ }
+ // 区间端点读的是同一个解析
+ assert_eq!(
+ read_time("17 Mar 2020").map(|(t, p)| (t.date_naive().to_string(), p)),
+ Some(("2020-03-17".to_string(), "day"))
+ );
}
#[test]
diff --git a/crates/utopia-extract/src/normalize.rs b/crates/utopia-extract/src/normalize.rs
index e26f9df7..e2abbae4 100644
--- a/crates/utopia-extract/src/normalize.rs
+++ b/crates/utopia-extract/src/normalize.rs
@@ -9,7 +9,7 @@
//! 每条规则做了什么都返回给服务端记进丢弃表:违约多常见、出在哪个模型,量得出来,
//! 契约该怎么改看数说话。
-use crate::{parse_time, ExtractedEntity, ExtractedFact, Extraction};
+use crate::{read_time, ExtractedEntity, ExtractedFact, Extraction};
use std::collections::HashSet;
/// 形状检查做了什么;服务端按条记信号
@@ -229,9 +229,10 @@ fn value_fact(
}
}
-/// 一侧写的是契约格式的时间(`YYYY` / `YYYY-MM` / `YYYY-MM-DD`,带时区的时刻)
-fn is_contract_time(s: &str) -> bool {
- parse_time(s.trim()).is_some()
+/// 一侧写的是一个时间:规则 3 的格式(`YYYY` / `YYYY-MM` / `YYYY-MM-DD`,带时区的时刻),
+/// 或写法说得清是哪天的日期(`written_date`,#688)
+fn names_a_time(s: &str) -> bool {
+ read_time(s.trim()).is_some()
}
/// 引文不在这一块、却在附上的文件开头里的事实:丢掉,连同因此没人引用的声明。
@@ -355,7 +356,7 @@ pub fn normalize_facts(x: &mut Extraction) -> Vec<Normalization> {
// ---- 主语是时间 ----
let subject =
handle_name(f.subject_ref.as_ref()).unwrap_or_else(|| f.subject.trim().to_string());
- if is_contract_time(&subject) {
+ if names_a_time(&subject) {
out.push(Normalization::TimeAsSubject {
predicate: f.predicate.clone(),
written: subject,
@@ -383,7 +384,7 @@ pub fn normalize_facts(x: &mut Extraction) -> Vec<Normalization> {
}
// ---- 宾语是时间 ----
- if let Some(o) = object.as_deref().filter(|o| is_contract_time(o)) {
+ if let Some(o) = object.as_deref().filter(|o| names_a_time(o)) {
if values.is_empty() {
// 没带数:写出来的那段就是值。`2028`(「2028 年起上线」)、`4000`(人数)都解析
// 得成年份,从前整条丢掉,一条信息就没了。宾语那个声明没人引用,下面按孤点去掉
diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rs
index 3089bf35..e54a12f7 100644
--- a/crates/utopia-server/src/extraction.rs
+++ b/crates/utopia-server/src/extraction.rs
@@ -1583,30 +1583,8 @@ async fn run(state: &AppState, document_id: Uuid, proposer: Proposer) -> anyhow:
.await;
continue;
}
- let from = f.valid_from.as_deref().and_then(utopia_extract::parse_time);
- let to = f.valid_to.as_deref().and_then(utopia_extract::parse_time);
- // **两端各记各的粒度**(见 `facts.valid_to_precision`)。从前一个精度列描述两个端点,
- // 于是「2020 年开始、2023-05-06 结束」这种只能共用一个值。
- //
- // 模型给的 valid_to = "unknown" 表示**原文说它结束了、但没说哪天**。
- // parse_time 解不出它(本来就不是日期),落在这里显式认掉——
- // 不认的话它退化成 None,那条事实就又变回"仍在持续"了
- let ended_unknown = f
- .valid_to
- .as_deref()
- .map(str::trim)
- .is_some_and(|v| v.eq_ignore_ascii_case(utopia_store::graph::ENDED_UNKNOWN));
- let validity = utopia_store::graph::Validity {
- from: from.map(|(t, _)| t),
- from_precision: from.map(|(_, p)| p),
- to: to.map(|(t, _)| t),
- to_precision: to
- .map(|(_, p)| p)
- .or(ended_unknown.then_some(utopia_store::graph::ENDED_UNKNOWN)),
- // 这次观察出自哪一天的文档(0022):没起点的事实从它起成立,结束了
- // 不知哪天的到它为止。没有文档日期就是记下的此刻——账本能给的最好的
- attested_at: doc.doc_time,
- };
+ let validity =
+ validity_of(f.valid_from.as_deref(), f.valid_to.as_deref(), doc.doc_time);
// 属性事实:谓词命中属性 → 字面值通道。datatype 校验失败宁缺勿脏;
// domain 校验(含子类上溯)挡住"把 salary 挂到 Organization"这类张冠李戴。
@@ -2946,6 +2924,38 @@ fn undeclared_beside_value(
///
/// "2015"、"2023-03"、"6" 认;"杭州"、"首席技术官"、"3M"、"V3" 不认。
/// 调用方还额外要求模型**没有**把它声明成实体——两道门一起过才算数。
+/// 模型给的区间两端 → 落库的有效区间。
+///
+/// **两端各记各的粒度**(见 `facts.valid_to_precision`)。从前一个精度列描述两个端点,
+/// 于是「2020 年开始、2023-05-06 结束」这种只能共用一个值。两端都用 `read_time` 读:
+/// 规则 3 的格式,或写法说得清是哪天的日期(#688),精度随写了几位。
+///
+/// 模型给的 valid_to = "unknown" 表示**原文说它结束了、但没说哪天**。
+/// read_time 解不出它(本来就不是日期),落在这里显式认掉——
+/// 不认的话它退化成 None,那条事实就又变回"仍在持续"了
+fn validity_of(
+ valid_from: Option<&str>,
+ valid_to: Option<&str>,
+ doc_time: Option<chrono::DateTime<chrono::Utc>>,
+) -> utopia_store::graph::Validity<'static> {
+ let from = valid_from.and_then(utopia_extract::read_time);
+ let to = valid_to.and_then(utopia_extract::read_time);
+ let ended_unknown = valid_to
+ .map(str::trim)
+ .is_some_and(|v| v.eq_ignore_ascii_case(utopia_store::graph::ENDED_UNKNOWN));
+ utopia_store::graph::Validity {
+ from: from.map(|(t, _)| t),
+ from_precision: from.map(|(_, p)| p),
+ to: to.map(|(t, _)| t),
+ to_precision: to
+ .map(|(_, p)| p)
+ .or(ended_unknown.then_some(utopia_store::graph::ENDED_UNKNOWN)),
+ // 这次观察出自哪一天的文档(0022):没起点的事实从它起成立,结束了
+ // 不知哪天的到它为止。没有文档日期就是记下的此刻——账本能给的最好的
+ attested_at: doc_time,
+ }
+}
+
fn looks_literal(s: &str) -> bool {
let s = s.trim();
if s.is_empty() {
@@ -2966,8 +2976,8 @@ fn looks_literal(s: &str) -> bool {
if utopia_extract::parse_quantity(s).is_some() {
return true;
}
- // 日期:复用抽取侧那个解析器,它认 2015 / 2015-03 / 2015-03-01 等
- utopia_extract::parse_time(s).is_some()
+ // 日期:复用抽取侧那个解析器,它认 2015 / 2015-03 / 2015-03-01,也认写出来的日期(#688)
+ utopia_extract::read_time(s).is_some()
}
/// 提示词里那三段清单:类、关系、属性。
@@ -3939,7 +3949,7 @@ mod tests {
use super::{
incomplete_reason, looks_literal, no_ref_name_binding, referenced_entity, resolve_bare,
- resolve_handle, BoundEntity, NoRefNameBinding,
+ resolve_handle, validity_of, BoundEntity, NoRefNameBinding,
};
use std::collections::HashMap;
use uuid::Uuid;
@@ -3960,6 +3970,10 @@ mod tests {
"€1.5 million",
"52%",
"35,000",
+ // 合同照原文写的日期(#688)
+ "June 23, 2020",
+ "17 Mar. 2020",
+ "2020年3月17日",
] {
assert!(looks_literal(yes), "{yes} 该认成字面值");
}
@@ -3983,6 +3997,31 @@ mod tests {
}
}
+ /// 区间两端照合同原文写(#688):读成日期,精度随写了几位;「unknown」仍是结束了不知哪天
+ #[test]
+ fn a_written_start_keeps_the_precision_it_was_written_with() {
+ let day = validity_of(Some("June 8, 2020"), None, None);
+ assert_eq!(
+ day.from.map(|t| t.date_naive().to_string()).as_deref(),
+ Some("2020-06-08")
+ );
+ assert_eq!(day.from_precision, Some("day"));
+ assert!(!day.has_ended());
+
+ let month = validity_of(Some("March 2020"), Some("17 Mar. 2021"), None);
+ assert_eq!(month.from_precision, Some("month"));
+ assert_eq!(
+ month.to.map(|t| t.date_naive().to_string()).as_deref(),
+ Some("2021-03-17")
+ );
+ assert_eq!(month.to_precision, Some("day"));
+
+ // 说不清几月几号的不当起点
+ let ambiguous = validity_of(Some("03/04/2020"), Some("unknown"), None);
+ assert_eq!((ambiguous.from, ambiguous.from_precision), (None, None));
+ assert_eq!(ambiguous.to_precision, Some("unknown"));
+ }
+
#[test]
fn no_ref_names_bypass_legacy_map_only_after_two_handle_claims() {
let (a, b) = (Uuid::now_v7(), Uuid::now_v7());