Skip to content

World's first open-source enterprise world model.

The agent's tools get the second clock (#350)

WaylandYang619061e0e289
diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rs
index a2bf589b..bb734267 100644
--- a/crates/utopia-server/src/api/chat.rs
+++ b/crates/utopia-server/src/api/chat.rs
@@ -231,7 +231,11 @@ pub(super) fn base_tools() -> serde_json::Value {
"parameters": {
"type": "object",
"properties": {
- "query": { "type": "string", "description": "Search query, phrased in the corpus language." }
+ "query": { "type": "string", "description": "Search query, phrased in the corpus language." },
+ "as_of": {
+ "type": "string",
+ "description": "Optional RECORD-time moment (YYYY-MM-DD or RFC3339): search only what the knowledge base held at that moment — earlier versions of documents, documents deleted since. Full-text recall stays current, so hits are correct but may be incomplete. Omit for the current base."
+ }
},
"required": ["query"]
}
@@ -308,6 +312,10 @@ pub(super) fn base_tools() -> serde_json::Value {
"type": "string",
"description": "Optional as-of date (YYYY-MM-DD). Only facts valid on \
this date are returned. Omit for the full history."
+ },
+ "as_of": {
+ "type": "string",
+ "description": "Optional RECORD-time moment (YYYY-MM-DD or RFC3339): the facts as the knowledge base held them at that moment, before later corrections, retractions and merges. Use for 'what did we think / know / have on record as of <date>' and 'before <event> arrived'. Independent of `at`: `at` is when something was true, `as_of` is when we believed it. Omit for today's understanding."
}
},
"required": ["entity_id"]
@@ -357,9 +365,9 @@ const SYSTEM_PROMPT: &str = "You are the assistant of Utopia, a temporal knowled
search_chunks returns short excerpts of the best-matching sections only. When a hit is \
clearly the right document but the excerpt does not carry the answer, read the whole \
document with get_document before saying the knowledge base does not have it.\n\
- The graph has TWO independent time axes, and each graph tool reads exactly one:\n\
- - World time — when something was true. Read with entity_facts (`at` = as of that date).\n\
- - Record time — when we came to believe it, and when we revised it. Read with changes.\n\
+ The graph has TWO independent time axes:\n\
+ - World time — when something was true. entity_facts(`at` = as of that date).\n\
+ - Record time — when we came to believe it, and when we revised it. entity_facts and search_chunks take `as_of` = the base as it stood at that moment, before later corrections, retractions and merges; changes lists what moved in a window.\n\
\"Who was CTO in 2019\" is world time; \"what did we learn last month\" and \"what did \
we get wrong\" are record time. The same fact has a position on both.\n\
Boundary: search_docs answers questions about Utopia itself (features, ingestion, \
@@ -382,7 +390,7 @@ 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. 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.\n\
2b. For \"what changed / what is new / what did we get wrong since <date>\", call changes — \
it needs no entity. Name the document a correction came from in plain prose. Graph tools \
return no [n] numbers and no URLs, so never write a bracketed citation or a placeholder \
diff --git a/crates/utopia-server/src/api/tools.rs b/crates/utopia-server/src/api/tools.rs
index 45c46755..16be2021 100644
--- a/crates/utopia-server/src/api/tools.rs
+++ b/crates/utopia-server/src/api/tools.rs
@@ -106,13 +106,16 @@ pub async fn search_chunks(
// 必填参数由 `chat::check_call` 在派发之前挡下,所以这里不再回落到
// 用户那句原话——回落产出的是一个看起来没问题的错误答案
let q = args["query"].as_str().unwrap_or_default().to_string();
+ // 记录轴(0019 / #347):只搜那一刻库里有的东西。全文那一路仍是"现在",
+ // 命中不会错但会缺——retrieval.rs 的头上写了
+ let as_of = args["as_of"].as_str().and_then(parse_when);
let chunks = retrieval::hybrid(
ctx.state,
ctx.kb_id,
ctx.workspace_id,
&q,
SEARCH_TOP_K,
- None,
+ as_of,
)
.await
.unwrap_or_default();
@@ -300,18 +303,18 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolRe
let id = args["entity_id"]
.as_str()
.and_then(|s| s.parse::<Uuid>().ok());
- // as-of 过滤:T 时刻有效 = 起点不晚于 T(或未知)且终点晚于 T(或开放)
- let at = args["at"]
- .as_str()
- .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
- .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc());
+ // 世界轴过滤:T 时刻有效 = 起点不晚于 T(或未知)且终点晚于 T(或开放)
+ let at = args["at"].as_str().and_then(parse_when);
+ // 记录轴(0019 / #347):那一刻**我们持有**的事实。两根轴两个参数,绝不合成
+ // 一个——合起来就会拿「三月的世界,以今天的认知」去答「三月的世界,以三月的认知」
+ let as_of = args["as_of"].as_str().and_then(parse_when);
let Some(id) = id else {
return (
"Invalid entity_id (expected the uuid returned by find_entities).".to_string(),
json!({ "kind": "facts", "label": "?", "detail": "invalid id" }),
);
};
- match utopia_store::graph::entity_detail(&ctx.state.pool, ctx.kb_id, id, None).await {
+ match utopia_store::graph::entity_detail(&ctx.state.pool, ctx.kb_id, id, as_of).await {
Ok((node, mut facts)) => {
if let Some(t) = at {
facts.retain(|f| {
@@ -330,9 +333,22 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolRe
} else {
facts.iter().map(fact_line).collect::<Vec<_>>().join("\n")
};
- let detail = match at {
- Some(t) => format!("{} facts as of {}", facts.len(), t.format("%Y-%m-%d")),
- None => format!("{} facts", facts.len()),
+ let detail = match (at, as_of) {
+ (Some(t), Some(r)) => format!(
+ "{} facts at {}, as recorded by {}",
+ facts.len(),
+ t.format("%Y-%m-%d"),
+ r.format("%Y-%m-%d")
+ ),
+ (Some(t), None) => format!("{} facts as of {}", facts.len(), t.format("%Y-%m-%d")),
+ (None, Some(r)) => {
+ format!(
+ "{} facts as recorded by {}",
+ facts.len(),
+ r.format("%Y-%m-%d")
+ )
+ }
+ (None, None) => format!("{} facts", facts.len()),
};
(
text,
@@ -571,6 +587,18 @@ fn fact_line(f: &EntityFact) -> String {
format!("{core}{range} [{}%]", (f.confidence * 100.0).round() as i32)
}
+/// 时刻参数:`YYYY-MM-DD` 或 RFC3339。`at` 与 `as_of` 共用一个解析——记录轴上的
+/// 时刻常常是一个带时间的戳("第一波灌完那一刻"),日期粒度装不下它
+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());
+ }
+ chrono::DateTime::parse_from_rfc3339(s)
+ .ok()
+ .map(|t| t.with_timezone(&chrono::Utc))
+}
+
/// 字面值宾语给模型看的样子:`{value, unit}` → "28000 CNY",布尔 → ✓/✗,
/// 映射那类 `{summary}` → 摘要本身。与 `web/src/pages/Graph.tsx::fmtObjectValue` 同一条规则,
/// 两边分叉的话,人看到的和模型看到的就不是同一个值
@@ -707,6 +735,21 @@ mod tests {
s.parse().unwrap()
}
+ // --- parse_when -------------------------------------------------------------
+
+ /// `at` 与 `as_of` 共用一个解析:日期按当天零点,RFC3339 原样;别的一律 None,
+ /// 不猜——猜出来的时刻会安静地把问题答到另一天上
+ #[test]
+ fn a_moment_is_a_date_or_an_rfc3339_stamp_and_nothing_else() {
+ assert_eq!(parse_when("2024-08-01"), Some(t("2024-08-01T00:00:00Z")));
+ assert_eq!(
+ parse_when(" 2026-09-05T02:43:24.197Z "),
+ Some(t("2026-09-05T02:43:24.197Z"))
+ );
+ assert_eq!(parse_when("August 2024"), None);
+ assert_eq!(parse_when(""), None);
+ }
+
// --- changes_window -----------------------------------------------------
/// 说"到 3 月 31 日为止"的人要的是**含 31 日**。SQL 那头是 `< end`,
diff --git a/web/src/docs/mcp.md b/web/src/docs/mcp.md
index 462329e9..7fecd235 100644
--- a/web/src/docs/mcp.md
+++ b/web/src/docs/mcp.md
@@ -37,15 +37,15 @@ Three methods are served:
| Tool | What it answers |
|---|---|
-| `search_chunks` | Full-text + semantic search over the base's documents. Returns the six best-matching passages, each cut at 800 characters and carrying its `document_id` |
+| `search_chunks` | Full-text + semantic search over the base's documents. Returns the six best-matching passages, each cut at 800 characters and carrying its `document_id`. Pass `as_of` to search the base as it stood at that moment — earlier versions, documents deleted since; full-text recall stays current, so hits are right but may be incomplete |
| `get_document` | The full text of one document, all sections in order, by `document_id`. Use it when a search hit is the right document but the excerpt does not carry the answer. Capped at 24,000 characters, and says so when it cuts |
| `find_entities` | Entities by (partial) name: id, type, and a disambiguator when several share a name |
-| `entity_facts` | One entity's facts with validity ranges. Pass `at` (a date) to see the world as of that day; this is the tool for "who was X in 2024" |
+| `entity_facts` | One entity's facts with validity ranges. Pass `at` (a date) to see the world as of that day; this is the tool for "who was X in 2024". Pass `as_of` (a date or an RFC3339 moment) to see the facts **as the base held them then**, before later corrections, retractions and merges — "what did we have on record before the memo arrived". The two combine: `at` for the date asked about, `as_of` for when |
| `changes` | What the graph learned or revised in a window of **record** time: asserted, corrected, rejected, merged. Needs no entity; use it when the question names a period, not a subject |
| `search_docs` | Utopia's own manual, for questions about how the platform works. Never the user's documents |
| `remember` | Record one sentence into the base's memory. **Needs a `write` token held by an editor**; a token without it does not see this tool in `tools/list`, and calling it anyway says why |
-The two time axes matter here. `entity_facts` reads **world time** (when something was true); `changes` reads **record time** (when Utopia came to believe it, and when it revised that belief). An agent that confuses them will answer "what happened in March" with "what we learned in March".
+The two time axes matter here. `at` reads **world time** (when something was true); `as_of` reads **record time** (what Utopia held at that moment, before it revised it), and `changes` lists what moved on that axis in a window. They are separate parameters on purpose: folded into one they would answer "what happened in March" with "what we learned in March", and both look plausible.
## What an agent records waits for a nod