Skip to content

armgit / Wake

Public Imported from GitHub
0

All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.

Rust

feat(context): tell new sessions where each agent left off

Corey Chiu6704465d7438
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 2eb1f56..d0d2e37 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -9,7 +9,7 @@
{
"name": "wake",
"source": "./plugins/wake",
- "description": "Every new session starts with this project's recent sessions (from Claude Code, Codex and the other agents Wake indexes), and Wake's MCP tools let Claude search and read any earlier session. Needs the Wake app."
+ "description": "Every new session starts knowing where your agents left off in this project (Claude Code, Codex and the other agents Wake indexes, each with its last question and reply), and Wake's MCP tools let Claude search and read any earlier session. Needs the Wake app."
}
]
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f04accd..ed8c65e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,7 +2,7 @@
## [Unreleased]
-- New: Every new Claude Code session can start with the project's recent sessions from Wake — install the Wake plugin with one command, and it adds Wake's MCP tools too. Codex gets the same through Codex hooks. Both are in Settings → Connect
+- New: New Claude Code and Codex sessions can start knowing where your agents left off in the project — the latest sessions from Claude Code, Codex, Cursor and the rest, each with its last question and reply. For Claude Code, install the Wake plugin with one command (it adds Wake's MCP tools too); Codex gets it through Codex hooks. Both are in Settings → Connect
- Fix: Looking up a project's sessions from a folder that has no history of its own no longer returns sessions started in your home folder or at the filesystem root
- Update: Copy buttons in Settings → Connect are icons now; hover one to see what it copies
- Fix: Search results show the text around each match, with every search term highlighted, instead of a dozen characters
diff --git a/README.md b/README.md
index c31ec6b..64b6e5f 100644
--- a/README.md
+++ b/README.md
@@ -134,7 +134,7 @@ wake-cli refresh # update the index while Wake
It prints what the MCP tools return, asserted byte for byte in the test suite apart from a trailing newline the CLI adds, so an agent driving it through a shell sees what a connected one does. Full reference in [docs/cli.md](docs/cli.md).
-To make an agent reach for it without being told, install the bundled skill with `npx skills add iAmCorey/Wake` (or copy `skills/wake/` into `~/.claude/skills/wake/`). Every new session can also start with the project's recent sessions already in context: for Claude Code, `claude plugin marketplace add iAmCorey/Wake && claude plugin install wake@wake` installs the Wake plugin, which does this and adds Wake's MCP tools in one go ([Claude Code plugin](docs/cli.md#claude-code-plugin)); Codex gets the same through [Codex hooks](docs/cli.md#codex-hooks). Both are in Settings → Connect.
+To make an agent reach for it without being told, install the bundled skill with `npx skills add iAmCorey/Wake` (or copy `skills/wake/` into `~/.claude/skills/wake/`). Every new session can also start knowing where your agents left off in the project — Claude Code, Codex and the rest, each with its last question and reply: for Claude Code, `claude plugin marketplace add iAmCorey/Wake && claude plugin install wake@wake` installs the Wake plugin, which does this and adds Wake's MCP tools in one go ([Claude Code plugin](docs/cli.md#claude-code-plugin)); Codex gets the same through [Codex hooks](docs/cli.md#codex-hooks). Both are in Settings → Connect.
## Zoom
diff --git a/crates/wake-core/src/adapters/mod.rs b/crates/wake-core/src/adapters/mod.rs
index c8a82df..89641e8 100644
--- a/crates/wake-core/src/adapters/mod.rs
+++ b/crates/wake-core/src/adapters/mod.rs
@@ -624,6 +624,27 @@ fn units_from_messages(messages: &[TranscriptMessage]) -> Vec<IndexUnit> {
.collect()
}
+/// `units_from_messages` 的反向,新会话开场的交接从索引里取最后一问一答用
+/// (`Store::last_exchange`):用户那句话按标题同款清洗、slash 命令写回 `/name args`,清洗后为空
+/// 的(只剩命令输出之类)不算。两边的写法一起改,下面的测试卡着
+pub(crate) fn unit_prompt(text: &str) -> Option<String> {
+ Some(parse_utils::clean_prompt_line(text)).filter(|p| !p.is_empty())
+}
+
+/// 见 `unit_prompt`。单元 = 消息正文 + 换行 + 工具行,所以首行为空就是只有工具调用的消息,
+/// 不算回复;否则取正文里第一行有字的,代码块的边界行(带语言名的 ```rust 也是)与分隔线不算。
+/// 回复以代码块开头时取到的是块里的第一行——不跳过整块去找后面的话:单元里正文后面紧跟着
+/// 工具行,跳过去很可能取到 "Bash git push"
+pub(crate) fn unit_reply(text: &str) -> Option<&str> {
+ if text.lines().next().is_none_or(|l| l.trim().is_empty()) {
+ return None;
+ }
+ text.lines().find(|l| {
+ let l = l.trim_start();
+ !l.starts_with("```") && !l.starts_with("~~~") && l.chars().any(char::is_alphanumeric)
+ })
+}
+
/// agent 在这些消息里查 Wake 的每一次调用:units_from_messages 把这些调用从索引里
/// 跳过,这里按同一判据逐次记下来(所在消息的 seq 与时间、走的接入、用的工具)落
/// wake_lookups 表——mcp-roadmap 定的"MCP 接入有没有真实使用"的信号,过滤掉又不记,
@@ -1309,6 +1330,42 @@ mod tests {
}
}
+ #[test]
+ fn units_read_back_into_the_last_question_and_reply() {
+ let units = units_from_messages(&[
+ msg(0, "", &[("Bash", "git diff")]),
+ msg(
+ 1,
+ "```\nDone: pushed to main.\n```",
+ &[("Bash", "git push")],
+ ),
+ msg(2, "```rust\nfn main() {}\n```", &[("Bash", "cargo run")]),
+ ]);
+ assert_eq!(unit_reply(&units[0].text), None, "只有工具调用不算回复");
+ assert_eq!(unit_reply(&units[1].text), Some("Done: pushed to main."));
+ assert_eq!(
+ unit_reply(&units[2].text),
+ Some("fn main() {}"),
+ "带语言名的代码块边界不是回复"
+ );
+ assert_eq!(
+ unit_prompt(
+ "<command-message>review</command-message>\n<command-name>/review</command-name>\n<command-args>--base main</command-args>"
+ )
+ .as_deref(),
+ Some("/review --base main")
+ );
+ assert_eq!(
+ unit_prompt("<command-name>/compact</command-name>").as_deref(),
+ Some("/compact")
+ );
+ assert_eq!(
+ unit_prompt("<local-command-stdout>Set model to opus</local-command-stdout>"),
+ None,
+ "命令输出不是人说的话"
+ );
+ }
+
#[test]
fn wake_lookups_stay_out_of_the_index() {
let messages = [
diff --git a/crates/wake-core/src/adapters/parse_utils.rs b/crates/wake-core/src/adapters/parse_utils.rs
index 9469e00..8822d17 100644
--- a/crates/wake-core/src/adapters/parse_utils.rs
+++ b/crates/wake-core/src/adapters/parse_utils.rs
@@ -1055,6 +1055,19 @@ pub fn epoch_ms(n: f64) -> i64 {
/// 清洗标题候选:剥 slash-command 壳与 system-reminder 等标签,压单行截断。空串=不可用
pub fn clean_title_candidate(raw: &str) -> String {
+ clean_user_text(raw, false)
+}
+
+/// 用户那句话折成一行(新会话开场交接里的 "last asked"):与标题同一套清洗,只是 slash 命令
+/// 写回用户敲的样子 `/name args`——标题只留参数,交接里要看得出是哪条命令。空串 = 不是人说的
+/// 话(只剩 `/model` 一类命令的输出等)
+pub fn clean_prompt_line(raw: &str) -> String {
+ clean_user_text(raw, true)
+}
+
+/// 两者共用的清洗;`whole_command` 定 slash 命令写成 `/name args`,还是只留参数(没有参数退
+/// 命令名)
+fn clean_user_text(raw: &str, whole_command: bool) -> String {
let mut s = strip_tag_block(raw, "system-reminder");
s = strip_tag_block(&s, "local-command-caveat");
s = strip_tag_block(&s, "local-command-stdout");
@@ -1062,10 +1075,11 @@ pub fn clean_title_candidate(raw: &str) -> String {
let args = extract_tag(&s, "command-args");
let name = extract_tag(&s, "command-name");
if args.is_some() || name.is_some() {
- s = args
- .filter(|a| !a.trim().is_empty())
- .or(name)
- .unwrap_or_default();
+ let args = args.filter(|a| !a.trim().is_empty());
+ s = match (whole_command, name, args) {
+ (true, Some(name), args) => format!("{name} {}", args.unwrap_or_default()),
+ (_, name, args) => args.or(name).unwrap_or_default(),
+ };
}
// 去掉残余短标签
let mut out = String::with_capacity(s.len());
@@ -1094,22 +1108,7 @@ pub fn clean_title_candidate(raw: &str) -> String {
out.push(c);
}
}
- let compact = out
- .replace(IMAGE_PLACEHOLDER, " ")
- .split_whitespace()
- .collect::<Vec<_>>()
- .join(" ");
- if compact.is_empty() {
- return String::new();
- }
- let chars: Vec<char> = compact.chars().collect();
- if chars.len() > MAX_TITLE {
- let mut t: String = chars[..MAX_TITLE].iter().collect();
- t.push('…');
- t
- } else {
- compact
- }
+ crate::text::one_line(&out.replace(IMAGE_PLACEHOLDER, " "), MAX_TITLE)
}
fn strip_tag_block(s: &str, tag: &str) -> String {
diff --git a/crates/wake-core/src/bin/wake_cli.rs b/crates/wake-core/src/bin/wake_cli.rs
index ee8a886..102f987 100644
--- a/crates/wake-core/src/bin/wake_cli.rs
+++ b/crates/wake-core/src/bin/wake_cli.rs
@@ -97,7 +97,7 @@ fn context(db: &Option<PathBuf>) -> ExitCode {
Ok(dir) => dir,
Err(e) => return write(refuse(format!("cannot read the current directory: {e}"))),
};
- // 只读库里的会话行、不读会话文件,不必把 roster 建起来(与 setup 同理);库不存在或
+ // 只读索引(会话行与消息单元)、不读会话文件,不必把 roster 建起来(与 setup 同理);库不存在或
// 太老由 open_read_only 给出 "launch Wake once"。哪天要读会话文件了,改回 open_index
let store = match Store::open_read_only(&db_path(db)) {
Ok(store) => store,
diff --git a/crates/wake-core/src/cli.rs b/crates/wake-core/src/cli.rs
index 605d13a..aaa6ac0 100644
--- a/crates/wake-core/src/cli.rs
+++ b/crates/wake-core/src/cli.rs
@@ -117,7 +117,7 @@ const PLAIN: &[PlainSpec] = &[
PlainSpec {
name: "context",
action: Action::Context,
- summary: "this folder's project, its recent sessions — for a session-start hook; prints nothing when there are none",
+ summary: "where your agents left off in this folder's project — for a session-start hook; prints nothing when there are none",
},
];
@@ -933,13 +933,13 @@ pub fn setup_text(f: &SetupFacts<'_>) -> String {
out.push_str(&snippet_section(
"Claude Code plugin",
&claude_plugin_snippet(),
- "Every new session starts with this project's recent sessions, and Claude gets\n\
- Wake's MCP tools to read them.",
+ "Every new session starts knowing where your agents left off in this project, and\n\
+ Claude gets Wake's MCP tools to read those sessions.",
));
out.push_str(&snippet_section(
"Codex hooks",
&codex_hooks_snippet(f.cli_bin),
- "Every new Codex session starts with this project's recent sessions.",
+ "Every new Codex session starts knowing where your agents left off in this project.",
));
}
// 片段按 agent 认,不按下标——那个顺序是 Connect 页的事;hint 也用它自己
diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rs
index d1072fa..ed617ec 100644
--- a/crates/wake-core/src/db.rs
+++ b/crates/wake-core/src/db.rs
@@ -1214,6 +1214,21 @@ impl Store {
.optional()?)
}
+ /// 一条会话停在哪:主线上最后一句用户提问与最后一条助手回复,各折成一行(单元怎么读回
+ /// 一句话在 `adapters::unit_prompt` / `unit_reply`,与写单元的 `units_from_messages` 放在
+ /// 一处)。新会话开场的交接用(`tools::session_start_context`)。两个角色各查各的:一次
+ /// 提问之后 agent 连跑几百步工具时,混在一起往回数会够不着那句提问,整场会话就被当成没
+ /// 提问(2026-10-10 Codex review);往回几百步都只有工具调用的,不给最后一答
+ pub fn last_exchange(&self, key: &str) -> Result<(Option<String>, Option<String>)> {
+ let conn = self.read.lock().unwrap();
+ Ok((
+ last_unit_of(&conn, key, Role::User, 50, crate::adapters::unit_prompt)?,
+ last_unit_of(&conn, key, Role::Assistant, 200, |text| {
+ crate::adapters::unit_reply(text).map(str::to_string)
+ })?,
+ ))
+ }
+
/// 路径 → 现行 key(watcher 增量的易主清理用)
pub fn key_for_path(&self, file_path: &str) -> Result<Option<String>> {
let conn = self.read.lock().unwrap();
@@ -2956,6 +2971,29 @@ const ROOT_SESSION_COLS_ALL: &str =
s.tokens_used, s.model, s.source, s.archived, s.file_path, s.file_size,
COALESCE(u.favorite,0), COALESCE(u.pinned,0), s.host";
+/// 主线上某个角色最近的单元里,第一个 `decode` 读得出话的(往回最多看 `limit` 条)。按 id
+/// 倒着走 idx_messages_session:同一会话的单元按 seq 顺序写入、追加只加在后面
+/// (`replace_units`),id 序就是 seq 序,不用排序,也不必把整条会话的正文读出来
+fn last_unit_of(
+ conn: &Connection,
+ key: &str,
+ role: Role,
+ limit: i64,
+ decode: impl Fn(&str) -> Option<String>,
+) -> Result<Option<String>> {
+ let mut stmt = conn.prepare_cached(
+ "SELECT text FROM messages WHERE session_key = ?1 AND sidechain_id IS NULL AND role = ?2 \
+ ORDER BY id DESC LIMIT ?3",
+ )?;
+ let mut rows = stmt.query(params![key, role.as_str(), limit])?;
+ while let Some(row) = rows.next()? {
+ if let Some(found) = decode(row.get_ref(0)?.as_str()?) {
+ return Ok(Some(found));
+ }
+ }
+ Ok(None)
+}
+
fn child_filter_sql(
filter: &SessionFilter,
parent_key: Option<&str>,
diff --git a/crates/wake-core/src/mcp/tools.rs b/crates/wake-core/src/mcp/tools.rs
index 303dfaf..5094825 100644
--- a/crates/wake-core/src/mcp/tools.rs
+++ b/crates/wake-core/src/mcp/tools.rs
@@ -5,7 +5,7 @@
//! 执行失败(坏 key、文件解析失败)是给 LLM 看的结果(`Failed` → isError)。
//! "没匹配上项目""没有结果"都不是错误,照常返回带提示的文本。
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use serde_json::{json, Value};
@@ -270,14 +270,21 @@ pub fn invoke(
}
/// 新会话开场注入几条、看多久以内的(`wake-cli context`;插件与 Codex 钩子都调它)
-const CONTEXT_SESSIONS: i64 = 5;
+const CONTEXT_SESSIONS: usize = 5;
const CONTEXT_DAYS: i64 = 14;
+/// 从多少条最近的会话里挑:每个 agent 先各取一条,再按时间补满
+const CONTEXT_CANDIDATES: i64 = 50;
+/// 最后一答折成一行的长度(最后一问与标题同用 MAX_TITLE)
+const CONTEXT_REPLY_CHARS: usize = 120;
/// 新会话开场的上下文(`wake-cli context`,Claude Code 插件与 Codex 的 SessionStart 钩子
-/// 调它):`dir` 所在项目最近两周的几条会话,查询与条目都是 wake_list_sessions 那一份
-/// (`recent_roots` / `push_session_lines`)。认不出项目、这段时间没有会话时给 None——钩子的
-/// 输出原样进 agent 的上下文,"没有结果"的提示与已知项目清单在这里只是噪音。不是 MCP 工具、
-/// 没有要逐字节对齐的另一面,只读库里的会话行、不读会话文件,所以不经 ToolContext、不要 roster
+/// 调它):`dir` 所在项目最近两周、各个 agent 停在哪——每条带最后一问与最后一答,好让新开的
+/// agent(多半是另一家)接得上。挑法:每个 agent 先各取最近一条、再按时间补满五条——只按
+/// 时间挑,用得最多的那一家会把别家整个挤出去,而交接要的恰恰是别家做到哪了;一句用户提问
+/// 都没有的会话(别的 agent 代跑的、刚开还没说话的)不列。认不出项目、这段时间没有会话时给
+/// None——钩子的输出原样进 agent 的上下文,"没有结果"的提示与已知项目清单在这里只是噪音。
+/// 筛选与 wake_list_sessions 同一份(`recent_roots`)。不是 MCP 工具、没有要逐字节对齐的另一面,
+/// 只读索引(会话行与消息单元)、不读会话文件,所以不经 ToolContext、不要 roster
pub fn session_start_context(
store: &Store,
dir: &std::path::Path,
@@ -286,32 +293,99 @@ pub fn session_start_context(
if project_paths.is_empty() {
return Ok(None);
}
- let since = crate::db::now_ms() - CONTEXT_DAYS * crate::cleanup::DAY;
- let (sessions, total) = recent_roots(
+ // 上层目录会匹配到底下的好几个项目(monorepo 根、~/Github),那时每条标出是哪个项目
+ let many_projects = project_paths.len() > 1;
+ let now = crate::db::now_ms();
+ let (candidates, total) = recent_roots(
store,
project_paths,
Vec::new(),
- Some(since),
+ Some(now - CONTEXT_DAYS * crate::cleanup::DAY),
false,
- CONTEXT_SESSIONS,
+ CONTEXT_CANDIDATES,
)?;
- if sessions.is_empty() {
+ // 每条候选一格:None = 还没问过,Some(None) = 一句提问都没有(不列),Some(Some(_)) = 选中。
+ // 先每个 agent 各取最近一条,再按时间补满;问过的不再问,够数就停
+ let mut picked: Vec<Option<Option<Exchange>>> = candidates.iter().map(|_| None).collect();
+ let mut agents = HashSet::new();
+ let mut count = 0;
+ for one_per_agent in [true, false] {
+ for (s, slot) in candidates.iter().zip(picked.iter_mut()) {
+ if count == CONTEXT_SESSIONS {
+ break;
+ }
+ if slot.is_some() || (one_per_agent && agents.contains(&s.agent)) {
+ continue;
+ }
+ let exchange = Exchange::of(store, &s.key)?;
+ if exchange.is_some() {
+ agents.insert(s.agent);
+ count += 1;
+ }
+ *slot = Some(exchange);
+ }
+ }
+ if count == 0 {
return Ok(None);
}
let mut out = format!(
- "Wake: {total} session{} in this project in the last {CONTEXT_DAYS} days{}:\n\n",
- plural(total),
- if total > sessions.len() as i64 {
- format!(", the {} most recent", sessions.len())
+ "Wake: recent sessions in this project, across your coding agents ({}):\n\n",
+ if total > count as i64 {
+ format!("{count} of {total} from the last {CONTEXT_DAYS} days")
} else {
- String::new()
+ format!("last {CONTEXT_DAYS} days")
}
);
- push_session_lines(&mut out, &sessions);
+ // 候选本来就按更新时间倒序
+ for (s, slot) in candidates.iter().zip(&picked) {
+ let Some(Some(x)) = slot else { continue };
+ out.push_str(&format!("- {}", s.agent.display_name()));
+ if many_projects && !s.project_name.is_empty() {
+ out.push_str(&format!(" · {}", s.project_name));
+ }
+ out.push_str(&format!(
+ " · {} · \"{}\" · `{}`\n last asked: \"{}\"\n",
+ ago(now, s.updated_at),
+ one_line(&s.title, MAX_TITLE),
+ s.key,
+ x.asked
+ ));
+ if let Some(reply) = &x.reply {
+ out.push_str(&format!(" last reply: \"{reply}\"\n"));
+ }
+ }
out.push_str("\nRead one with the wake_get_session tool, or run `wake-cli show <key>`.\n");
Ok(Some(out))
}
+/// 一条会话停在哪:最后一问与最后一答,各一行(`Store::last_exchange`)。一句用户提问都没有
+/// 就是 None——那条会话不进开场上下文
+struct Exchange {
+ asked: String,
+ reply: Option<String>,
+}
+
+impl Exchange {
+ fn of(store: &Store, key: &str) -> Result<Option<Self>, ToolError> {
+ let (asked, reply) = store.last_exchange(key)?;
+ Ok(asked.map(|asked| Self {
+ asked,
+ reply: reply.map(|r| one_line(&r, CONTEXT_REPLY_CHARS)),
+ }))
+ }
+}
+
+/// 开场注入里的时间:离现在多久(开场那一刻算的,读的人不用再换算日期)
+fn ago(now_ms: i64, t_ms: i64) -> String {
+ let mins = (now_ms - t_ms).max(0) / 60_000;
+ match mins {
+ 0 => "just now".to_string(),
+ m if m < 60 => format!("{m}m ago"),
+ m if m < 24 * 60 => format!("{}h ago", m / 60),
+ m => format!("{}d ago", m / (24 * 60)),
+ }
+}
+
// ---------------------------------------------------------------- 参数读取
fn str_arg<'a>(args: &'a Value, name: &str) -> Result<Option<&'a str>, ToolError> {
@@ -975,14 +1049,6 @@ fn recent_roots(
})?)
}
-/// 会话清单的条目,一条一行("- " + `session_line`)
-fn push_session_lines(out: &mut String, sessions: &[SessionMeta]) {
- for s in sessions {
- out.push_str("- ");
- out.push_str(&session_line(s));
- }
-}
-
fn list_sessions(ctx: &ToolContext, args: &Value) -> ToolResult {
let agents = agents_arg(args)?;
let since = since_arg(ctx, args)?;
@@ -1009,7 +1075,10 @@ fn list_sessions(ctx: &ToolContext, args: &Value) -> ToolResult {
plural(total),
sessions.len()
));
- push_session_lines(&mut out, &sessions);
+ for s in &sessions {
+ out.push_str("- ");
+ out.push_str(&session_line(s));
+ }
out.push_str("\nRead one with wake_get_session using its key.\n");
out.push_str(&index_note(ctx.store));
Ok(out)
@@ -1431,6 +1500,16 @@ fn get_session(ctx: &ToolContext, args: &Value) -> ToolResult {
mod tests {
use super::*;
+ #[test]
+ fn ago_reads_like_a_person_would_say_it() {
+ let now = 1_800_000_000_000;
+ assert_eq!(ago(now, now), "just now");
+ assert_eq!(ago(now, now + 5_000), "just now", "时钟略有偏差也不出负数");
+ assert_eq!(ago(now, now - 90_000), "1m ago");
+ assert_eq!(ago(now, now - 3 * 3_600_000), "3h ago");
+ assert_eq!(ago(now, now - 50 * 3_600_000), "2d ago");
+ }
+
#[test]
fn agent_names_parse_leniently() {
assert_eq!(parse_agent("claude-code"), Some(AgentId::ClaudeCode));
diff --git a/crates/wake-core/tests/cli.rs b/crates/wake-core/tests/cli.rs
index 03f44b6..74c9aa3 100644
--- a/crates/wake-core/tests/cli.rs
+++ b/crates/wake-core/tests/cli.rs
@@ -18,7 +18,7 @@ use wake_core::adapters::{create_adapter_roster_for, create_adapters_for, AgentA
use wake_core::cli;
use wake_core::db::{self, Store};
use wake_core::mcp::tools::{self, TranscriptCache};
-use wake_core::models::{SessionFilter, SessionMeta};
+use wake_core::models::{AgentId, Role, SessionFilter, SessionMeta};
use wake_core::scanner::{run_scan, NullEvents};
mod common;
@@ -758,11 +758,13 @@ fn refresh_refuses_when_only_remote_memories_would_be_lost() {
assert_eq!(left, 1, "远程记忆不许被清掉");
}
-/// `context` 给 SessionStart 钩子用:当前目录所在项目最近两周的会话,子目录归到所在项目;
-/// 认不出项目、两周内没有会话时一个字节都不输出、退 0——钩子的输出原样进 agent 的上下文。
-/// 家目录不当"所在项目":在家目录随手开的会话不该被塞进每个新项目
+/// `context` 给 SessionStart 钩子用:当前目录所在项目最近两周、各个 agent 停在哪(最后一问、
+/// 最后一答),子目录归到所在项目。每个 agent 先各取一条再按时间补满五条——常用的那一家
+/// 不能把别家挤出去;一句提问都没有的会话不列。认不出项目、两周内没有会话时一个字节都不
+/// 输出、退 0——钩子的输出原样进 agent 的上下文。家目录不当"所在项目":在家目录随手开的
+/// 会话不该被塞进每个新项目
#[test]
-fn context_prints_this_folders_recent_sessions_or_nothing() {
+fn context_shows_where_each_agent_left_off_or_nothing() {
let tmp = tempfile::tempdir().unwrap();
let home = std::fs::canonicalize(tmp.path()).unwrap();
let project = home.join("app");
@@ -773,19 +775,62 @@ fn context_prints_this_folders_recent_sessions_or_nothing() {
{
let store = Store::open(&db).unwrap();
let now = db::now_ms();
- let session = |id: &str, at: &Path, updated_at: i64| SessionMeta {
- project_path: at.to_string_lossy().into_owned(),
- created_at: updated_at,
- updated_at,
- ..common::meta(&format!("claude-code:{id}"), &format!("about {id}"))
+ let write = |key: &str, at: &Path, minutes_ago: i64, turns: &[(Role, &str)]| {
+ let updated_at = now - minutes_ago * 60_000;
+ let meta = SessionMeta {
+ agent: AgentId::from_str(key.split(':').next().unwrap()).unwrap(),
+ project_path: at.to_string_lossy().into_owned(),
+ created_at: updated_at,
+ updated_at,
+ ..common::meta(key, &format!("about {key}"))
+ };
+ let units: Vec<_> = turns
+ .iter()
+ .enumerate()
+ .map(|(seq, (role, text))| common::unit(seq as i64, *role, text))
+ .collect();
+ store.write_session(&meta, updated_at, &units).unwrap();
};
- store
- .write_meta_only(&[
- (session("recent", &project, now), 1),
- (session("stale", &project, now - 30 * 86_400_000), 1),
- (session("in-home", &home, now), 1),
- ])
- .unwrap();
+ // Claude Code 五条都比 Codex 那条新,只按时间挑 Codex 就进不来。每条最后一个用户单元
+ // 是 `/model` 一类命令的输出——不是人说的话,最后一问要往前找到真正的提问
+ for n in 1..=5 {
+ write(
+ &format!("claude-code:c{n}"),
+ &project,
+ n,
+ &[
+ (Role::User, &format!("ask c{n}")),
+ (Role::Assistant, &format!("did c{n}\nmore")),
+ (
+ Role::User,
+ "<local-command-stdout>Set model to opus</local-command-stdout>",
+ ),
+ ],
+ );
+ }
+ write(
+ "codex:review",
+ &project,
+ 2 * 24 * 60,
+ &[
+ (
+ Role::User,
+ "<command-message>review</command-message>\n<command-name>/review</command-name>\n<command-args>--base main</command-args>",
+ ),
+ (Role::Assistant, "Looks good overall"),
+ // 只有工具调用的消息:单元以换行开头,不算回复
+ (Role::Assistant, "\nBash git diff main"),
+ ],
+ );
+ // 一句提问都没有(别的 agent 代跑、刚开还没说话)
+ write("codex:silent", &project, 0, &[(Role::Assistant, "working")]);
+ write(
+ "claude-code:stale",
+ &project,
+ 30 * 24 * 60,
+ &[(Role::User, "old")],
+ );
+ write("claude-code:in-home", &home, 0, &[(Role::User, "hi")]);
}
let context = |dir: &Path| {
let (out, _, code) = cli_raw_with(&["--db", db.to_str().unwrap(), "context"], |cmd| {
@@ -796,10 +841,37 @@ fn context_prints_this_folders_recent_sessions_or_nothing() {
let (text, code) = context(&project.join("src"));
assert_eq!(code, Some(0));
assert!(
- text.starts_with("Wake: 1 session in this project in the last 14 days:"),
+ text.starts_with(
+ "Wake: recent sessions in this project, across your coding agents (5 of 7 from the last 14 days):"
+ ),
+ "{text}"
+ );
+ let at = |needle: &str| {
+ text.find(needle)
+ .unwrap_or_else(|| panic!("{needle} 不在: {text}"))
+ };
+ // 按时间排:c1 最新,Codex 那条最旧
+ assert!(
+ at("`claude-code:c1`") < at("`claude-code:c4`")
+ && at("`claude-code:c4`") < at("`codex:review`")
+ );
+ assert!(
+ !text.contains("claude-code:c5"),
+ "补满五条,c5 排不上: {text}"
+ );
+ assert!(
+ text.contains("last asked: \"ask c1\"\n last reply: \"did c1\"\n"),
"{text}"
);
- assert!(text.contains("`claude-code:recent`"), "{text}");
+ assert!(
+ text.contains("last asked: \"/review --base main\""),
+ "slash 命令写回原样: {text}"
+ );
+ assert!(
+ text.contains("last reply: \"Looks good overall\""),
+ "工具调用不算回复: {text}"
+ );
+ assert!(!text.contains("codex:silent"), "没有提问的会话不列: {text}");
assert!(!text.contains("stale"), "两周以前的不列: {text}");
assert!(!text.contains("in-home"), "家目录的会话不跟进来: {text}");
diff --git a/crates/wake-core/tests/common/mod.rs b/crates/wake-core/tests/common/mod.rs
index 7814c1d..6edd394 100644
--- a/crates/wake-core/tests/common/mod.rs
+++ b/crates/wake-core/tests/common/mod.rs
@@ -8,7 +8,7 @@ use std::fs;
use std::path::{Path, PathBuf};
use wake_core::db::{IndexLock, Ownership};
-use wake_core::models::{AgentId, SessionMeta};
+use wake_core::models::{AgentId, IndexUnit, Role, SessionMeta};
/// 一条最小的会话元数据(Claude Code、无模型无 token);测试按需用 `..meta(..)` 改字段。
/// SessionMeta 没有 Default,新字段只补这一处
@@ -36,6 +36,17 @@ pub fn meta(key: &str, title: &str) -> SessionMeta {
}
}
+/// 一个索引单元(主线、时间戳随 seq 递增);IndexUnit 同样没有 Default
+pub fn unit(seq: i64, role: Role, text: &str) -> IndexUnit {
+ IndexUnit {
+ seq,
+ sidechain_id: None,
+ role,
+ timestamp: Some(1_700_000_000_000 + seq),
+ text: text.to_string(),
+ }
+}
+
/// dsh 默认落盘的 zstd 多帧日志:首帧 header 行、次帧事件批,帧直接连接(写端每次 append
/// 一帧,解码器解到 EOF)
pub fn dsh_zstd(plain: &str) -> Vec<u8> {
diff --git a/crates/wake-core/tests/db_roundtrip.rs b/crates/wake-core/tests/db_roundtrip.rs
index 3e015bc..9c83d84 100644
--- a/crates/wake-core/tests/db_roundtrip.rs
+++ b/crates/wake-core/tests/db_roundtrip.rs
@@ -8,7 +8,7 @@ use wake_core::db::{self, IndexLock, Ownership, Store, Wait};
use wake_core::models::*;
mod common;
-use common::meta;
+use common::{meta, unit};
fn temp_store() -> (tempfile::TempDir, Store) {
let dir = tempfile::tempdir().expect("tempdir");
@@ -16,14 +16,30 @@ fn temp_store() -> (tempfile::TempDir, Store) {
(dir, store)
}
-fn unit(seq: i64, role: Role, text: &str) -> IndexUnit {
- IndexUnit {
- seq,
- sidechain_id: None,
- role,
- timestamp: Some(1_700_000_000_000 + seq),
- text: text.to_string(),
+/// 一次提问之后 agent 连跑几百步工具:最后一问照样找得到——会话不会被当成没提问、从新会话
+/// 开场的交接里消失;往回 200 条助手消息里一句话都没有的,不给最后一答
+#[test]
+fn last_exchange_survives_a_long_tool_run() {
+ let (_dir, store) = temp_store();
+ for (key, steps) in [("claude-code:long", 300), ("claude-code:short", 20)] {
+ let mut units = vec![
+ unit(0, Role::User, "refactor the parser"),
+ unit(1, Role::Assistant, "On it."),
+ ];
+ units.extend(
+ (2..steps).map(|seq| unit(seq, Role::Assistant, &format!("\nBash step {seq}"))),
+ );
+ store.write_session(&meta(key, key), 1, &units).unwrap();
}
+ let asked = Some("refactor the parser".to_string());
+ assert_eq!(
+ store.last_exchange("claude-code:long").unwrap(),
+ (asked.clone(), None)
+ );
+ assert_eq!(
+ store.last_exchange("claude-code:short").unwrap(),
+ (asked, Some("On it.".to_string()))
+ );
}
#[test]
diff --git a/docs/cli.md b/docs/cli.md
index d5bb0fb..7bbc624 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -122,14 +122,30 @@ To make this automatic instead of per-project, install the skill (see [Teaching
### `context`
-Prints the recent sessions of the project the current directory belongs to — up to five
-from the last 14 days, in the same lines `sessions` uses — and nothing at all when there
-are none:
+Prints where your coding agents left off in the project the current directory belongs to:
+up to five sessions from the last 14 days, each with its last question and the first line
+of its last reply. Every agent gets its latest session in before the rest are filled in by
+time, so the agent you use most cannot crowd out the others, and sessions without a single
+question in them (ones another agent ran for you, or ones nobody typed into yet) are left
+out. It prints nothing at all when there are none:
```bash
cd ~/Github/my-app && wake-cli context
```
+```text
+Wake: recent sessions in this project, across your coding agents (5 of 9 from the last 14 days):
+
+- Claude Code · 2h ago · "Fix the login redirect" · `claude-code:1b2c…`
+ last asked: "push it"
+ last reply: "Pushed to main: the redirect now keeps the original query string."
+- Codex · 1d ago · "Review the auth changes" · `codex:01a0…`
+ last asked: "/review --base main"
+ last reply: "Two issues: the session cookie is not marked Secure, and the logout route skips CSRF…"
+
+Read one with the wake_get_session tool, or run `wake-cli show <key>`.
+```
+
It is what the [Claude Code plugin](#claude-code-plugin) and the [Codex hooks](#codex-hooks) setup run: whatever the hook
prints lands in the new session's context, where a "no sessions" reply or a list of other
projects would only be noise. A subfolder counts as its project, as with `--project
@@ -275,13 +291,14 @@ install anything, or want the guidance to live in the repository.
## Claude Code plugin
-The Wake plugin starts every new Claude Code session with this project's recent sessions
-already in its context — from Claude Code, Codex and every other agent Wake indexes — so
-"continue from yesterday" needs no explaining, and it adds Wake's MCP tools so Claude can
-open any of them with `wake_get_session`. Underneath it is a session-start hook that runs
+The Wake plugin starts every new Claude Code session knowing where your agents left off in
+this project — Claude Code, Codex and every other agent Wake indexes, each session with its
+last question and reply — so "continue from yesterday" or "pick up what Codex was doing"
+needs no explaining, and it adds Wake's MCP tools so Claude can open any of them with
+`wake_get_session`. Underneath it is a session-start hook that runs
[`wake-cli context`](#context), which prints nothing in a project without recent history.
It needs Wake 0.8.9 or later and covers macOS and Linux. Settings → Connect shows the
-command with a Copy button.
+command with a copy button.
```bash
claude plugin marketplace add iAmCorey/Wake && claude plugin install wake@wake
diff --git a/docs/mcp.md b/docs/mcp.md
index 9ef362c..f9b07f6 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -22,8 +22,8 @@ Settings → Connect in Wake shows the exact path for your install with a copy b
claude mcp add --scope user wake -- "/Applications/Wake.app/Contents/MacOS/wake-mcp"
```
-Or install the Wake plugin instead, which adds this server and starts every new session with
-the project's recent sessions — `claude plugin marketplace add iAmCorey/Wake && claude plugin
+Or install the Wake plugin instead, which adds this server and starts every new session
+knowing where your agents left off in the project — `claude plugin marketplace add iAmCorey/Wake && claude plugin
install wake@wake` (see [Claude Code plugin](cli.md#claude-code-plugin)). Use one or the other, not
both, or the tools are listed twice.
@@ -90,8 +90,9 @@ Before asking me for context about this repository, check earlier sessions with
wake_list_sessions with the current directory, then wake_get_session for the relevant one.
```
-Claude Code and Codex can also be handed the project's recent sessions automatically when a
-session starts, through a hook that runs `wake-cli context` — see
+Claude Code and Codex can also be told where your agents left off in the project when a
+session starts — each recent session with its last question and reply — through a hook
+that runs `wake-cli context`; see
[Claude Code plugin](cli.md#claude-code-plugin) and [Codex hooks](cli.md#codex-hooks) in the
command-line guide. The Claude Code plugin brings this MCP server along.
diff --git a/plugins/wake/.claude-plugin/plugin.json b/plugins/wake/.claude-plugin/plugin.json
index 5dfbf36..b2c876f 100644
--- a/plugins/wake/.claude-plugin/plugin.json
+++ b/plugins/wake/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "wake",
"displayName": "Wake",
- "description": "Every new session starts with this project's recent sessions, and Wake's MCP tools let Claude search and read any earlier session from any coding agent. Read-only; needs the Wake app.",
+ "description": "Every new session starts knowing where your coding agents left off in this project, and Wake's MCP tools let Claude search and read any earlier session from any agent. Read-only; needs the Wake app.",
"author": {
"name": "Corey Chiu",
"url": "https://github.com/iAmCorey"
diff --git a/plugins/wake/scripts/session-start b/plugins/wake/scripts/session-start
index 059a954..3345c3f 100755
--- a/plugins/wake/scripts/session-start
+++ b/plugins/wake/scripts/session-start
@@ -1,6 +1,6 @@
#!/bin/sh
-# SessionStart hook: prints this project's recent sessions, which Claude Code adds to the
-# new session's context. `wake-cli context` prints nothing when the project has no recent
+# SessionStart hook: prints where your agents left off in this project, which Claude Code
+# adds to the new session's context. `wake-cli context` prints nothing when the project has no recent
# sessions. When Wake is not installed or has no index yet, this stays quiet too — a hook
# should never get in the way of starting a session.
cd "${CLAUDE_PROJECT_DIR:-.}" 2>/dev/null || exit 0