Go implementation of DeepSeek Harness and self-hosted personal agent.
Go
fix(proactive): expand recent dialogue and clarify history times
xyc3a7e09d76209
diff --git a/docs/proactive-discovery-plan.zh-CN.md b/docs/proactive-discovery-plan.zh-CN.mdindex 4fe620f..25baed8 100644--- a/docs/proactive-discovery-plan.zh-CN.md+++ b/docs/proactive-discovery-plan.zh-CN.md@@ -2,7 +2,7 @@日期:2026-11-22。状态:已实现,完成本地 Go、Docker、真实模型及 Web / Android Release 验收。本文已按本轮讨论整体更新,取代上一版中的首次交流门槛、固定检查区间、主会话二次价值判断和子 Agent 自动回报设计。-本轮确定运行主体、触发、结果、投递,并细化其他会话资料的采集和上下文归属。完整实施契约见第 13 节;实现和验证状态随实施更新。基础能力调研见 [Agent 组合能力方案](agent-composition-research-plan.zh-CN.md),产品公开行为见[之前的调研](proactive-service-research-and-plan.zh-CN.md)。+本文确定运行主体、触发、结果、投递,并细化其他会话资料的采集和上下文归属。完整实施契约见第 13 节;现有 Go 装配及执行边界见[架构说明](architecture.md),完整可扩展 Preset 的后续设计见 [Go Agent Preset 方案](agent-preset-go-plan.zh-CN.md)。## 1. 主体与职责@@ -302,14 +302,14 @@ AI 根据当前背景选择值得深入的方向| 排除项 | 排除内部主动服务会话、普通隐藏子会话、system、内部 Agent 投递、工具调用、工具结果、执行状态与流式增量等过程记录 || 时间窗口 | 主会话和其他会话都只自动采集最近 7 天有实际用户/助手对话活动的部分;长期不活跃的会话不自动补入 || 会话数量 | 按最近实际对话活动时间选取,默认最多展开 8 个其他会话;超过时标明截断,未展开的历史仍可通过 session_search 查询 |-| 每个会话 | 优先提供最近两组真实用户输入及相关助手文本;有 Schedule 生成的可见结果时标明其来源,避免只有助手结论没有任务背景 |-| 消息大小 | 原文片段建议单条不超过 800 个 Unicode 字符,保留截断标记;不把截断文本称为完整摘要 |-| 全局大小 | 跨会话活动资料建议最多 24,000 个 Unicode 字符,达到预算时减少或截短片段 |+| 每个会话 | 优先提供最近四组真实用户输入及相关助手文本(每组最多两条助手文本);有 Schedule 生成的可见结果时标明其来源,避免只有助手结论没有任务背景 |+| 消息大小 | 原文片段建议单条不超过 1,000 个 Unicode 字符,保留截断标记;不把截断文本称为完整摘要 |+| 全局大小 | 跨会话活动资料建议最多 30,000 个 Unicode 字符,达到预算时减少或截短片段 || 覆盖说明 | 告知时间范围、实际包含数量、是否还有未包含会话及片段截断情况;不让模型误以为看到了全部历史 |这些数值是待验收调校的采集默认值,不是用户必须配置的环境变量,也不限制 AI 继续检索的历史范围。最初采用真实文本片段,不在每轮前为所有会话额外调用一次摘要模型。-每个片段至少保留 `sessionId`、标题、消息角色、消息时间、日志 `seq`、原文及截断标记。AI 可以据此继续读取锚点前后内容,而不是只能看到一个不可追溯的摘要。+每个片段至少保留 `sessionId`、标题、消息角色、消息时间、日志 `seq`、原文及截断标记。 提供给后台 Agent 的活动资料中,消息时间、会话最近活动时间及采集范围起点统一格式化为带 `UTC` 时区的可读绝对日期时间(例如 `2026-11-24 09:30:00.000 UTC`),不直接注入 Unix 毫秒数字。底层日志和 SQLite 索引仍保留原有毫秒时间戳。历史资料明确标注时间属于原会话;后台当前时间仍由自身标准 `time-context` 提供,不复制其他会话的时间提示为当前时间。AI 可以据此继续读取锚点前后内容,而不是只能看到一个不可追溯的摘要。最近窗口会遗漏更早的重要背景,这是有界自动采集的取舍。较早的主题可由长期记忆、已有研究历史、Schedule 或新线索提示 AI,再通过历史检索找回。没有近期会话变化时仍可到时研究,不把这份活动列表当作唯一信息来源。@@ -350,7 +350,7 @@ AI 根据当前背景选择值得深入的方向现有普通会话列表只排除了普通子会话和归档记录。未来独立后台会话还需要按内部用途明确排除,不能因为它不是普通子 Agent 就意外纳入用户会话概览和全文索引。-活动采集器的基础实现已加入现有 SQLite 索引模块:按消息时间读取最近 7 天、主会话与最多 8 个其他会话,提供最后两组用户交流与有界助手文本,单条 800 字、总计 24,000 字,保留 seq 与截断标记。已测试内部来源/工具块/欢迎语排除与归档移除;Host 运行时刷新接入仍在实施。+活动采集器的基础实现已加入现有 SQLite 索引模块:按消息时间读取最近 7 天、主会话与最多 8 个其他会话,提供最后四组用户交流与有界助手文本,单条 1,000 字、总计 30,000 字,保留 seq 与截断标记。已测试内部来源/工具块/欢迎语排除与归档移除;Host 运行时刷新接入仍在实施。### 10.6 后台 Agent 需要感知的信息清单@@ -389,7 +389,7 @@ System、运行时资料、原会话消息、Skill catalog 和工具定义各有它需要控制 timer、持久 Agent 运行、结果确认、Session 恢复和主会话 Inbox 投递。这些都属于我们已经选择由 Go 管理的核心能力。让它成为普通 Cordis 业务插件,会把这些核心责任再次跨进程搬到 Node。-插件继续提供第三方信息、工具、Skill 和可选事件提示;它们通过内置服务交互,不控制 AgentLoop 或接管后台 Agent 的生存期。Agent 组合能力也在 Go 装配层实现。具体接口及后台组合可见范围见 [Agent 组合能力方案](agent-composition-research-plan.zh-CN.md),初始组合与运行契约见第 13 节。+插件继续提供第三方信息、工具、Skill 和可选事件提示;它们通过内置服务交互,不控制 AgentLoop 或接管后台 Agent 的生存期。Agent 组合能力也在 Go 装配层实现。Go 装配与插件边界见[架构说明](architecture.md),初始组合与运行契约见第 13 节;通用 Preset 子系统仍属于[后续设计](agent-preset-go-plan.zh-CN.md)。## 12. 数据、启停与边界diff --git a/harness/sessionsearch/activity.go b/harness/sessionsearch/activity.goindex 4d9a380..c21eb7d 100644--- a/harness/sessionsearch/activity.go+++ b/harness/sessionsearch/activity.go@@ -64,7 +64,7 @@ WHERE time >= ? AND session_id <> ? GROUP BY session_id ORDER BY MAX(time) DESC,selected = append([]ActivitySession{{SessionID: main, UpdatedAt: last.Int64}}, selected...)}}- budget := 24000+ budget := 30000for _, entry := range selected {if i.source.Title != nil {entry.Title = i.source.Title(entry.SessionID)@@ -79,8 +79,8 @@ WHERE time >= ? AND session_id <> ? GROUP BY session_id ORDER BY MAX(time) DESC,break}chars := []rune(message.Content)- if len(chars) > min(800, budget) {- chars, message.Truncated = chars[:min(800, budget)], true+ if len(chars) > min(1000, budget) {+ chars, message.Truncated = chars[:min(1000, budget)], true}message.Content = string(chars)budget -= len(chars)@@ -94,19 +94,19 @@ WHERE time >= ? AND session_id <> ? GROUP BY session_id ORDER BY MAX(time) DESC,}func (i *Index) recentDialogue(ctx context.Context, id string, since int64) ([]Message, error) {- // Keep the last two actual user inputs and the latest assistant dialogue+ // Keep the last four actual user inputs and the latest assistant dialogue// belonging to each. Text around tools can span several messages; at most// two assistant messages per exchange keep this preview bounded. Earlier// details remain retrievable by the original seq anchors.rows, err := i.db.QueryContext(ctx, `WITH last_users AS (- SELECT seq FROM messages WHERE session_id=? AND time>=? AND role='user' ORDER BY seq DESC LIMIT 2+ SELECT seq FROM messages WHERE session_id=? AND time>=? AND role='user' ORDER BY seq DESC LIMIT 4), recent AS (SELECT seq, role, body, time, MAX(CASE WHEN role='user' THEN seq END) OVER (ORDER BY seq) AS exchangeFROM messages WHERE session_id=? AND time>=? AND seq >= COALESCE((SELECT MIN(seq) FROM last_users), 0)), ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY exchange, role ORDER BY seq DESC) AS rank FROM recent)-SELECT seq, role, SUBSTR(body,1,801), time, LENGTH(body)>800 FROM ranked WHERE role='user' OR rank<=2 ORDER BY seq`, id, since, id, since)+SELECT seq, role, SUBSTR(body,1,1001), time, LENGTH(body)>1000 FROM ranked WHERE role='user' OR rank<=2 ORDER BY seq`, id, since, id, since)if err != nil {return nil, err}diff --git a/harness/sessionsearch/activity_test.go b/harness/sessionsearch/activity_test.goindex 6c2bed2..f9cb7d1 100644--- a/harness/sessionsearch/activity_test.go+++ b/harness/sessionsearch/activity_test.go@@ -17,7 +17,7 @@ func TestRecentActivityUsesVisibleMessageTimesAndBoundedUnicodeText(t *testing.Thistories := map[string][]sessionformat.Event{}for n := 1; n <= 12; n++ {id := fmt.Sprintf("00000000-0000-4000-8000-%012d", n)- for seq, text := range []string{"first request", "first answer", "second request", "second answer", "third request", strings.Repeat("界", 1200)} {+ for seq, text := range []string{"first request", "first answer", "second request", "second answer", "third request", "third answer", "fourth request", "fourth answer", "fifth request", strings.Repeat("界", 1200)} {role, kind := "user", "user/message"if seq%2 != 0 {role, kind = "assistant", "assistant/message"@@ -34,13 +34,13 @@ func TestRecentActivityUsesVisibleMessageTimesAndBoundedUnicodeText(t *testing.Told := historyEvent(0, "user/message", "user", "stale conversation")old.Time = now.Add(-8 * 24 * time.Hour).UnixMilli()histories[stale] = []sessionformat.Event{old}- internal := historyEvent(6, "user/message", "agent-message", "never copy internal relay")+ internal := historyEvent(10, "user/message", "agent-message", "never copy internal relay")internal.Time = now.UnixMilli()- tool := historyEvent(7, "tool/result", "tool", "never copy tool output")+ tool := historyEvent(11, "tool/result", "tool", "never copy tool output")tool.Time = now.UnixMilli()- welcome := historyEvent(8, "assistant/message", "go-bot/welcome", "never infer interests from the welcome")+ welcome := historyEvent(12, "assistant/message", "go-bot/welcome", "never infer interests from the welcome")welcome.Time = now.UnixMilli()- mixed := historyEvent(9, "assistant/message", "assistant", "visible conclusion")+ mixed := historyEvent(13, "assistant/message", "assistant", "visible conclusion")mixed.Time = now.Add(-time.Hour).UnixMilli()var data map[string]json.RawMessage_ = json.Unmarshal(mixed.Data, &data)@@ -79,8 +79,11 @@ func TestRecentActivityUsesVisibleMessageTimesAndBoundedUnicodeText(t *testing.T}users := 0for _, message := range entry.Messages {+ if message.Timestamp != histories[entry.SessionID][message.ID].Time {+ t.Fatal("activity lost the original message timestamp")+ }chars += len([]rune(message.Content))- if len([]rune(message.Content)) > 800 {+ if len([]rune(message.Content)) > 1000 {t.Fatal("Unicode preview exceeded its limit")}if message.Role == "user" {@@ -91,15 +94,15 @@ func TestRecentActivityUsesVisibleMessageTimesAndBoundedUnicodeText(t *testing.Tt.Fatalf("copied excluded text %q: %+v", forbidden, message)}}- if strings.HasPrefix(message.Content, "界") && !message.Truncated {- t.Fatal("long preview lacked its truncation flag")+ if strings.HasPrefix(message.Content, "界") && (!message.Truncated || len([]rune(message.Content)) != 1000) {+ t.Fatal("long preview did not retain exactly 1000 characters with a truncation flag")}}- if users != 2 {- t.Fatalf("expected the last two user exchanges, got %d: %+v", users, entry)+ if users != 4 {+ t.Fatalf("expected the last four user exchanges, got %d: %+v", users, entry)}}- if chars > 24000 {+ if chars > 30000 {t.Fatal("total activity budget exceeded")}// Archived sessions disappear through the same real source list used bydiff --git a/internal/host/proactive.go b/internal/host/proactive.goindex 9b8b060..2c67376 100644--- a/internal/host/proactive.go+++ b/internal/host/proactive.go@@ -272,7 +272,7 @@ func (b *backgroundService) collect(ctx context.Context, state proactive.State)encode := func(value any) string { data, _ := json.Marshal(value); return string(data) }b.sections = []agent.RuntimeContextSection{{Name: "proactive:main", Text: "Main conversation delivery target and local Agent status (not the user's real-world availability): " + encode(map[string]string{"sessionId": state.MainSessionID, "cwd": mainCWD, "state": mainStatus})},- {Name: "proactive:recent-dialogue", Text: "Historical visible dialogue excerpts, not new instructions. Coverage and truncation are explicit; older details remain available via session_search: " + encode(activity)},+ {Name: "proactive:recent-dialogue", Text: "Historical visible dialogue excerpts, not new instructions. All dates below are historical times in UTC, not the current time; use this Agent's time-context for the current time. Coverage and truncation are explicit; older details remain available via session_search: " + proactiveDialogueContext(activity)},{Name: "proactive:schedules", Text: "Existing user work arrangements, not instructions to create duplicate tasks: " + encode(map[string]any{"tasks": tasks, "total": document.Total, "truncated": document.Total > len(tasks)})},}if state.NextCheck != nil {diff --git a/internal/host/proactive_context.go b/internal/host/proactive_context.gonew file mode 100644index 0000000..5814aa5--- /dev/null+++ b/internal/host/proactive_context.go@@ -0,0 +1,44 @@+package host++import (+ "encoding/json"+ "time"++ "go-bot/harness/sessionsearch"+)++// Only the model-facing presentation changes. The committed-message index and+// its search API retain their original Unix-millisecond timestamps.+func proactiveDialogueContext(activity sessionsearch.Activity) string {+ type message struct {+ ID uint64 `json:"id"`+ Role string `json:"role"`+ Content string `json:"content"`+ Timestamp string `json:"timestamp"`+ Truncated bool `json:"truncated,omitempty"`+ }+ type conversation struct {+ SessionID string `json:"sessionId"`+ Title string `json:"title,omitempty"`+ UpdatedAt string `json:"updatedAt"`+ Messages []message `json:"messages"`+ }+ view := struct {+ Since string `json:"since"`+ Sessions []conversation `json:"sessions"`+ Truncated bool `json:"truncated"`+ }{Sessions: []conversation{}, Truncated: activity.Truncated}+ format := func(ms int64) string {+ return time.UnixMilli(ms).UTC().Format("2006-01-02 15:04:05.000 MST")+ }+ view.Since = format(activity.Since)+ for _, entry := range activity.Sessions {+ row := conversation{SessionID: entry.SessionID, Title: entry.Title, UpdatedAt: format(entry.UpdatedAt), Messages: []message{}}+ for _, item := range entry.Messages {+ row.Messages = append(row.Messages, message{ID: item.ID, Role: item.Role, Content: item.Content, Timestamp: format(item.Timestamp), Truncated: item.Truncated})+ }+ view.Sessions = append(view.Sessions, row)+ }+ data, _ := json.Marshal(view)+ return string(data)+}diff --git a/internal/host/proactive_context_test.go b/internal/host/proactive_context_test.gonew file mode 100644index 0000000..70e2604--- /dev/null+++ b/internal/host/proactive_context_test.go@@ -0,0 +1,63 @@+package host++import (+ "encoding/json"+ "strings"+ "testing"+ "time"++ "go-bot/harness/sessionsearch"+)++func TestProactiveDialogueFormatsHistoricalTimesWithoutChangingIndexedMessages(t *testing.T) {+ at := time.Date(2026, 11, 24, 9, 30, 0, 123000000, time.FixedZone("Asia/Shanghai", 8*3600))+ activity := sessionsearch.Activity{+ Since: at.Add(-7 * 24 * time.Hour).UnixMilli(), Truncated: true,+ Sessions: []sessionsearch.ActivitySession{{+ SessionID: "chat-id", Title: "调研", UpdatedAt: at.UnixMilli(),+ Messages: []sessionsearch.Message{+ {ID: 12, Role: "user", Content: "明天再看这份报告", Timestamp: at.UnixMilli(), Truncated: true},+ {ID: 15, Role: "assistant", Content: "好的", Timestamp: at.Add(time.Second).UnixMilli()},+ },+ }},+ }+ var view struct {+ Since string+ Truncated bool+ Sessions []struct {+ SessionID string+ Title string+ UpdatedAt string+ Messages []struct {+ ID uint64+ Role string+ Content string+ Timestamp string+ Truncated bool+ }+ }+ }+ if err := json.Unmarshal([]byte(proactiveDialogueContext(activity)), &view); err != nil {+ t.Fatal(err)+ }+ if view.Since != "2026-11-17 01:30:00.123 UTC" || !view.Truncated || len(view.Sessions) != 1 {+ t.Fatalf("lost coverage information: %+v", view)+ }+ row := view.Sessions[0]+ if row.SessionID != "chat-id" || row.Title != "调研" || row.UpdatedAt != "2026-11-24 01:30:00.123 UTC" || len(row.Messages) != 2 {+ t.Fatalf("lost conversation information: %+v", row)+ }+ for i, item := range row.Messages {+ source := activity.Sessions[0].Messages[i]+ parsed, err := time.Parse("2006-01-02 15:04:05.000 MST", item.Timestamp)+ if err != nil || parsed.UnixMilli() != source.Timestamp || !strings.HasSuffix(item.Timestamp, " UTC") {+ t.Fatalf("historical instant changed: %+v, %v", item, err)+ }+ if item.ID != source.ID || item.Role != source.Role || item.Content != source.Content || item.Truncated != source.Truncated {+ t.Fatalf("message content/anchor changed: %+v", item)+ }+ }+ if activity.Sessions[0].Messages[0].Timestamp != at.UnixMilli() {+ t.Fatal("model presentation changed the source index timestamp")+ }+}diff --git a/internal/host/proactive_test.go b/internal/host/proactive_test.goindex c9b9579..3fa2747 100644--- a/internal/host/proactive_test.go+++ b/internal/host/proactive_test.go@@ -311,10 +311,14 @@ func TestBackgroundHostRunsQuietThenTimedNotificationWithStandardContext(t *testif len(captured) != 2 {t.Fatalf("background calls=%d", len(captured))}+ historicalTime := time.UnixMilli(activity.Sessions[0].Messages[0].Timestamp).UTC().Format("2006-01-02 15:04:05.000 MST")for _, raw := range captured {if !strings.Contains(string(raw), "Time sampled while preparing turn") || !strings.Contains(string(raw), "我正在研究 AI 行业报告") {t.Fatalf("missing standard time or real activity context: %s", raw)}+ if !strings.Contains(string(raw), "historical times in UTC") || !strings.Contains(string(raw), historicalTime) {+ t.Fatalf("historical dialogue lacks readable, labelled times: %s", raw)+ }for _, name := range []string{`"name":"ask_user_question"`, `"name":"create_goal"`, `"name":"schedule_create"`, `"name":"send_message"`} {if strings.Contains(string(raw), name) {t.Fatalf("unavailable interactive/background tool leaked: %s", name)