From 9917601c1e32274adda32ec28893196041ff0405 Mon Sep 17 00:00:00 2001 From: Chai Jie Date: Mon, 26 Oct 2026 15:18:22 +0800 Subject: [PATCH] feat: import seekmoon conversation history SeekMoon keeps one JSONL transcript per conversation inside the workspace it belongs to (/.openseek/sessions//openseek_session-.jsonl), so unlike every other platform here there is no single home directory to scan: the roots come from the desktop's own ~/.openseek/workspaces.json. Read maps what the user saw: `user`, `assistant` (prose and its tool calls kept on one message) and `tool_result` (paired by tool_call_id). `runtime_notice`, `terminal` and the assistant's `reasoning_content` are app bookkeeping and are skipped; an unknown kind or a malformed line becomes a warning, never a failed session. Uploading needs the platform's agent token, which the seekmoon installer writes into host-mcp.json. Until the backend accepts the platform, the resolver says so and names both ways to supply one, instead of failing with a bare path error. The "Use one of: ..." hint in the import commands now comes from the registry rather than a repeated literal at two call sites. Co-Authored-By: SeekMoon --- CHANGELOG.md | 11 + cli/cmd/imports/conversations.go | 4 +- cli/internal/importer/conversation/evt.go | 69 ++++ .../importer/conversation/platforms.go | 16 +- .../importer/conversation/registry.go | 5 + .../importer/conversation/seekmoon.go | 304 ++++++++++++++++++ .../importer/conversation/seekmoon_test.go | 284 ++++++++++++++++ .../testdata/seekmoon_sample.jsonl | 6 + cli/internal/importer/conversation/types.go | 1 + 9 files changed, 697 insertions(+), 3 deletions(-) create mode 100644 cli/internal/importer/conversation/seekmoon.go create mode 100644 cli/internal/importer/conversation/seekmoon_test.go create mode 100644 cli/internal/importer/conversation/testdata/seekmoon_sample.jsonl diff --git a/CHANGELOG.md b/CHANGELOG.md index e1a8b04..24f0007 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,17 @@ the open-source home for EverMe CLI and agent plugins. ### CLI +- Add a SeekMoon reader to `evercli import conversations`. SeekMoon keeps one + transcript per conversation inside the workspace it belongs to + (`/.openseek/sessions//openseek_session-.jsonl`), + so the scan roots come from SeekMoon's own `workspaces.json` rather than a + home directory. `user`, `assistant` (with its tool calls) and `tool_result` + records are imported; `runtime_notice`, `terminal` and the assistant's + `reasoning_content` are skipped as app bookkeeping. Uploading needs the + platform's agent token from SeekMoon's `host-mcp.json`, which + `plugin install seekmoon` writes. +- Derive the "Use one of: …" platform hint from the registry instead of + repeating the list at each call site. - Sync the `cli/` Go tree to the `evercli` v0.32.0 release. Earlier public snapshots trailed the published binaries; the tree now matches what `npm install -g @everme/cli` and the release archives ship. diff --git a/cli/cmd/imports/conversations.go b/cli/cmd/imports/conversations.go index d0c6d3a..ac9ae18 100644 --- a/cli/cmd/imports/conversations.go +++ b/cli/cmd/imports/conversations.go @@ -474,7 +474,7 @@ Use --path to override the scan root for a specific platform.`, } else { ids, perr := conversation.ParsePlatforms(requested) if perr != nil { - return deps.Out.Err(output.Invalid(perr.Error(), "Use one of: claude-code, codex, hermes, openclaw, markdown, kimicode, raven, workbuddy")) + return deps.Out.Err(output.Invalid(perr.Error(), "Use one of: "+conversation.PlatformList())) } platformIDs = ids } @@ -652,7 +652,7 @@ Flags: } else { ids, perr := conversation.ParsePlatforms(effectivePlatforms) if perr != nil { - return deps.Out.Err(output.Invalid(perr.Error(), "Use one of: claude-code, codex, hermes, openclaw, markdown, kimicode, raven, workbuddy")) + return deps.Out.Err(output.Invalid(perr.Error(), "Use one of: "+conversation.PlatformList())) } platformIDs = ids } diff --git a/cli/internal/importer/conversation/evt.go b/cli/internal/importer/conversation/evt.go index 5cbcc1e..3b0ac14 100644 --- a/cli/internal/importer/conversation/evt.go +++ b/cli/internal/importer/conversation/evt.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "path/filepath" + "runtime" "strings" "github.com/pelletier/go-toml/v2" @@ -192,6 +193,72 @@ func resolveWorkBuddyEvt() (string, error) { return tok, nil } +// seekMoonRuntimeDir returns SeekMoon's runtime directory, where the desktop +// keeps both host-mcp.json and workspaces.json. Mirrors +// cli/internal/plugin/seekmoon.go seekMoonConfigDir, env override included. +func seekMoonRuntimeDir() (string, error) { + if dir := os.Getenv("EVERCLI_SEEKMOON_CONFIG_DIR"); dir != "" { + return dir, nil + } + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + switch runtime.GOOS { + case "darwin": + return filepath.Join(home, "Library", "Application Support", "SeekMoon"), nil + case "windows": + if appdata, err := os.UserConfigDir(); err == nil && appdata != "" { + return filepath.Join(appdata, "SeekMoon"), nil + } + return filepath.Join(home, "AppData", "Roaming", "SeekMoon"), nil + default: + return filepath.Join(home, ".config", "SeekMoon"), nil + } +} + +// seekMoonEvtHint is the actionable half of every seekmoon credential error. +// The usual source of the token is `plugin install`, which needs the EverMe +// backend to accept the platform, so say what to do when that is not available. +func seekMoonEvtHint(path string) string { + return "run `evercli plugin install seekmoon` (it needs the EverMe backend to accept the " + + "seekmoon platform), or add EVERME_AGENT_TOKEN to mcpServers[\"everme-memory\"].env in " + path +} + +// resolveSeekMoonEvt reads EVERME_AGENT_TOKEN from SeekMoon's host-mcp.json at +// mcpServers["everme-memory"].env — the entry the seekmoon installer writes +// through the shared mcpWriter (cli/internal/plugin/seekmoon.go buildEntry). +// SeekMoon keeps its own `seekmoon` entry in that file too; only ours carries +// the EverMe credential. +func resolveSeekMoonEvt() (string, error) { + dir, err := seekMoonRuntimeDir() + if err != nil { + return "", fmt.Errorf("resolve seekmoon runtime dir: %w", err) + } + path := filepath.Join(dir, "host-mcp.json") + raw, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("read seekmoon config %s: %w; %s", path, err, seekMoonEvtHint(path)) + } + var cfg struct { + McpServers map[string]struct { + Env map[string]string `json:"env"` + } `json:"mcpServers"` + } + if err := json.Unmarshal(raw, &cfg); err != nil { + return "", fmt.Errorf("parse seekmoon config %s: %w", path, err) + } + entry, ok := cfg.McpServers["everme-memory"] + if !ok { + return "", fmt.Errorf(`seekmoon config %s has no mcpServers["everme-memory"] entry; %s`, path, seekMoonEvtHint(path)) + } + tok := strings.TrimSpace(entry.Env["EVERME_AGENT_TOKEN"]) + if tok == "" { + return "", fmt.Errorf(`EVERME_AGENT_TOKEN is empty in mcpServers["everme-memory"].env of %s; %s`, path, seekMoonEvtHint(path)) + } + return tok, nil +} + func envOr(key, def string) string { if v := os.Getenv(key); v != "" { return v @@ -236,6 +303,8 @@ func ResolveEvt(p PlatformID) (string, error) { return resolveRavenEvt() case PlatformWorkBuddy: return resolveWorkBuddyEvt() + case PlatformSeekMoon: + return resolveSeekMoonEvt() } path, ok := platformEnvFile(p) if !ok { diff --git a/cli/internal/importer/conversation/platforms.go b/cli/internal/importer/conversation/platforms.go index 4b38427..f426f74 100644 --- a/cli/internal/importer/conversation/platforms.go +++ b/cli/internal/importer/conversation/platforms.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "path/filepath" + "sort" "strings" ) @@ -18,6 +19,19 @@ var knownPlatforms = map[PlatformID]struct{}{ PlatformKimicode: {}, PlatformRaven: {}, PlatformWorkBuddy: {}, + PlatformSeekMoon: {}, +} + +// PlatformList renders the known platform names for CLI hints. Callers use it +// instead of repeating the list, so a new platform cannot be accepted by +// ParsePlatforms while the hint still tells the user it does not exist. +func PlatformList() string { + names := make([]string, 0, len(knownPlatforms)) + for p := range knownPlatforms { + names = append(names, string(p)) + } + sort.Strings(names) + return strings.Join(names, ", ") } // IsKnownPlatform reports whether p is one of the supported platform names. @@ -34,7 +48,7 @@ func ParsePlatforms(names []string) ([]PlatformID, error) { for _, n := range names { p := PlatformID(strings.TrimSpace(n)) if !IsKnownPlatform(p) { - return nil, fmt.Errorf("unknown platform %q (known: claude-code, codex, hermes, openclaw, markdown, kimicode, raven, workbuddy)", n) + return nil, fmt.Errorf("unknown platform %q (known: %s)", n, PlatformList()) } ids = append(ids, p) } diff --git a/cli/internal/importer/conversation/registry.go b/cli/internal/importer/conversation/registry.go index 34ccf59..a7a5130 100644 --- a/cli/internal/importer/conversation/registry.go +++ b/cli/internal/importer/conversation/registry.go @@ -22,6 +22,7 @@ func DefaultRegistry() *Registry { NewKimicodeScanner(), NewRavenScanner(), NewWorkBuddyScanner(), + NewSeekMoonScanner(), }, } } @@ -75,6 +76,10 @@ func DefaultRoots(p PlatformID) []string { // env var name, so the two doors into ~/.workbuddy agree. base := envOr("EVERCLI_WORKBUDDY_CONFIG_DIR", filepath.Join(home, ".workbuddy")) return []string{filepath.Join(base, "projects")} + case PlatformSeekMoon: + // SeekMoon keeps sessions with their workspace, not in one home dir: + // the roots come from the desktop's own workspace registry. + return seekMoonSessionRoots() case PlatformMarkdown: // A markdown file's owning agent is the agent whose local folder // contains it; scan the agent home dirs (not generic doc dirs) so md diff --git a/cli/internal/importer/conversation/seekmoon.go b/cli/internal/importer/conversation/seekmoon.go new file mode 100644 index 0000000..3f7cb58 --- /dev/null +++ b/cli/internal/importer/conversation/seekmoon.go @@ -0,0 +1,304 @@ +package conversation + +import ( + "bufio" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "time" +) + +// SeekMoonScanner parses SeekMoon (moonbitlang/openseek) conversation +// transcripts. +// +// SeekMoon keeps one JSONL file per conversation, inside the session directory +// of the workspace the conversation belongs to: +// +// /.openseek/sessions//openseek_session-.jsonl +// +// There is no single home directory to scan — sessions live with their +// workspace — so the roots come from the desktop's own workspace registry +// (see seekMoonSessionRoots). The session directory also holds `jobs/`, +// `scratch/`, `session.lock` and `prediction.json`; none of them is a +// transcript. +// +// Line 1 is a session header carrying `version`, `id` and the full +// `system_prompt`. The prompt is instructions, not conversation, so it is +// dropped; `id` becomes the origin id the conversation id is derived from. +// Every later line is one record: +// +// {"sequence":N,"ts":,"item":{"kind":"…","payload":{…}}} +// +// with these kinds: +// +// user payload.content, payload.submission_id +// assistant payload.content (may be empty), payload.tool_calls +// [{id,name,arguments}], payload.reasoning_content +// (internal chain-of-thought), payload.usage +// tool_result payload.tool_call_id, payload.tool_name, payload.content, +// payload.is_error, payload.brief, payload.data +// runtime_notice payload.content — app notices (background jobs finishing) +// terminal payload.kind, payload.message — app state +// +// `reasoning_content` and the two bookkeeping kinds are skipped: like every +// other scanner here, only what the user actually saw is imported. +type SeekMoonScanner struct{} + +var _ Scanner = (*SeekMoonScanner)(nil) + +func NewSeekMoonScanner() *SeekMoonScanner { return &SeekMoonScanner{} } + +func (s *SeekMoonScanner) Platform() PlatformID { return PlatformSeekMoon } + +const ( + // seekMoonSessionFilePrefix marks a transcript; the session id follows. + seekMoonSessionFilePrefix = "openseek_session-" + seekMoonSessionFileSuffix = ".jsonl" +) + +func (s *SeekMoonScanner) Scan(roots []string) ([]Item, error) { + var items []Item + for _, root := range roots { + if _, err := os.Stat(root); os.IsNotExist(err) { + continue + } + err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { + if err != nil { + return nil + } + if d.IsDir() { + // `jobs` keeps tool output, `scratch` the session's temp files; + // neither holds a transcript. + switch d.Name() { + case "jobs", "scratch": + return filepath.SkipDir + } + return nil + } + name := d.Name() + if !strings.HasPrefix(name, seekMoonSessionFilePrefix) || + !strings.HasSuffix(name, seekMoonSessionFileSuffix) { + return nil + } + info, infoErr := d.Info() + if infoErr != nil || info == nil { + return nil // skip unreadable entry + } + items = append(items, Item{ + Platform: PlatformSeekMoon, + Path: path, + Status: "ready", + SizeBytes: info.Size(), + UpdatedAt: info.ModTime().UTC().Format(time.RFC3339), + }) + return nil + }) + if err != nil { + return nil, err + } + } + return items, nil +} + +func (s *SeekMoonScanner) Read(item Item) (*Conversation, error) { + f, err := os.Open(item.Path) + if err != nil { + return nil, err + } + defer f.Close() + + conv := &Conversation{Item: item} + scanner := bufio.NewScanner(f) + // A transcript records whole tool results (job output, file reads), so a + // single line can be far past bufio's default cap. + scanner.Buffer(make([]byte, 0, 1024*1024), 64*1024*1024) + + // File mtime is the deterministic fallback base for records that carry no + // ts — never time.Now(), which would break re-import idempotency. + var fallbackBase int64 + if fi, statErr := os.Stat(item.Path); statErr == nil { + fallbackBase = fi.ModTime().UnixMilli() + } else { + fallbackBase = time.Unix(0, 0).UnixMilli() + } + + const maxRunes = 8000 + lineNum := 0 + originID := "" + + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if line == "" { + continue + } + lineNum++ + + var rec map[string]any + if err := json.Unmarshal([]byte(line), &rec); err != nil { + conv.Warnings = append(conv.Warnings, fmt.Sprintf("line %d: json decode error: %v", lineNum, err)) + continue + } + + item := objectMapCC(rec["item"]) + if item == nil { + // Header line: keep the session id, drop the system prompt. + if originID == "" { + if id, ok := rec["id"].(string); ok { + originID = strings.TrimSpace(id) + } + } + continue + } + + payload := objectMapCC(item["payload"]) + ts := normalizeTimestampCC(rec["ts"], fallbackBase+int64(lineNum)) + + switch kind := stringFieldCC(item, "kind"); kind { + case "user": + text := truncateRunesCC(strings.TrimSpace(stringFieldCC(payload, "content")), maxRunes) + if text == "" { + continue + } + conv.Messages = append(conv.Messages, AgentMemoryMessage{ + Role: "user", + Timestamp: ts, + Content: Redact(text), + }) + + case "assistant": + // One record can carry both prose and tool calls; keep them on a + // single message so the tool call stays next to what asked for it. + text := truncateRunesCC(strings.TrimSpace(stringFieldCC(payload, "content")), maxRunes) + calls := seekMoonToolCalls(payload["tool_calls"], ts) + if text == "" && len(calls) == 0 { + // reasoning-only turn: nothing the user saw. + continue + } + msg := AgentMemoryMessage{Role: "assistant", Timestamp: ts, ToolCalls: calls} + if text != "" { + msg.Content = Redact(text) + } + conv.Messages = append(conv.Messages, msg) + + case "tool_result": + callID := strings.TrimSpace(stringFieldCC(payload, "tool_call_id")) + if callID == "" { + conv.Warnings = append(conv.Warnings, fmt.Sprintf("line %d: tool_result missing tool_call_id, dropped", lineNum)) + continue + } + text := truncateRunesCC(strings.TrimSpace(stringFieldCC(payload, "content")), maxRunes) + if text == "" { + text = "tool result" + } + conv.Messages = append(conv.Messages, AgentMemoryMessage{ + Role: "tool", + Timestamp: ts, + ToolCallID: callID, + Content: Redact(text), + }) + + case "runtime_notice", "terminal": + // App bookkeeping (a background job finishing, a turn's terminal + // state) — not something the user or the assistant said. + + default: + if kind != "" { + conv.Warnings = append(conv.Warnings, fmt.Sprintf("line %d: unknown record kind %q, skipped", lineNum, kind)) + } + } + } + if err := scanner.Err(); err != nil { + return nil, err + } + + setStartedAtFromMessages(conv) + conv.ID = ConversationID(PlatformSeekMoon, originID, item.Path) + return conv, nil +} + +// seekMoonToolCalls maps a record's tool_calls array onto the BFF shape. +// Arguments are JSON text in the transcript; Redact runs before they leave the +// machine like every other scanner's. +func seekMoonToolCalls(v any, ts int64) []AgentMemoryToolCall { + raw, ok := v.([]any) + if !ok || len(raw) == 0 { + return nil + } + calls := make([]AgentMemoryToolCall, 0, len(raw)) + for i, entry := range raw { + m := objectMapCC(entry) + if m == nil { + continue + } + calls = append(calls, AgentMemoryToolCall{ + ID: firstNonEmptyCC(stringFieldCC(m, "id"), fmt.Sprintf("seekmoon_tool_%d_%d", ts, i)), + Type: "function", + Name: firstNonEmptyCC(stringFieldCC(m, "name"), "unknown"), + Arguments: Redact(argumentsStringCC(m["arguments"])), + }) + } + if len(calls) == 0 { + return nil + } + return calls +} + +// seekMoonSessionRoots resolves one session root per workspace SeekMoon knows. +// The desktop records its workspaces in ~/.openseek/workspaces.json, and each +// workspace keeps its own sessions, so a single home-directory scan cannot see +// them. EVERCLI_SEEKMOON_WORKSPACES (path-list) overrides the registry, and +// EVERCLI_SEEKMOON_HOME moves the .openseek directory itself (tests). +func seekMoonSessionRoots() []string { + if list := os.Getenv("EVERCLI_SEEKMOON_WORKSPACES"); list != "" { + var roots []string + for _, ws := range filepath.SplitList(list) { + if ws = strings.TrimSpace(ws); ws != "" { + roots = append(roots, seekMoonSessionsDir(ws)) + } + } + return roots + } + + home, err := seekMoonHome() + if err != nil { + return nil + } + raw, err := os.ReadFile(filepath.Join(home, "workspaces.json")) + if err != nil { + return nil + } + var registry struct { + Workspaces []string `json:"workspaces"` + } + if err := json.Unmarshal(raw, ®istry); err != nil { + return nil + } + roots := make([]string, 0, len(registry.Workspaces)) + for _, ws := range registry.Workspaces { + if ws = strings.TrimSpace(ws); ws != "" { + roots = append(roots, seekMoonSessionsDir(ws)) + } + } + return roots +} + +// seekMoonSessionsDir is where one workspace keeps its session directories. +func seekMoonSessionsDir(workspace string) string { + return filepath.Join(workspace, ".openseek", "sessions") +} + +// seekMoonHome is the user-level .openseek directory, which holds the +// desktop's workspace registry. It is not the app runtime directory: that one +// (host-mcp.json, engine-settings.json) lives under Application Support. +func seekMoonHome() (string, error) { + if dir := os.Getenv("EVERCLI_SEEKMOON_HOME"); dir != "" { + return dir, nil + } + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + return filepath.Join(home, ".openseek"), nil +} diff --git a/cli/internal/importer/conversation/seekmoon_test.go b/cli/internal/importer/conversation/seekmoon_test.go new file mode 100644 index 0000000..79f40ee --- /dev/null +++ b/cli/internal/importer/conversation/seekmoon_test.go @@ -0,0 +1,284 @@ +package conversation + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +// writeSeekMoonSession lays out one workspace the way the desktop does: +// /.openseek/sessions//openseek_session-.jsonl plus the session's +// non-transcript neighbours. +func writeSeekMoonSession(t *testing.T, ws, id, body string) string { + t.Helper() + dir := filepath.Join(ws, ".openseek", "sessions", id) + for _, sub := range []string{"jobs", "scratch"} { + if err := os.MkdirAll(filepath.Join(dir, sub), 0o700); err != nil { + t.Fatalf("mkdir %s: %v", sub, err) + } + } + path := filepath.Join(dir, "openseek_session-"+id+".jsonl") + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatalf("write transcript: %v", err) + } + // Neighbours that must never be mistaken for a transcript. + for name, content := range map[string]string{ + "prediction.json": `{"predicted":[]}`, + "session.lock": "", + "jobs/uuid-1.json": `{"id":"job"}`, + "scratch/notes.md": "# scratch", + } { + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil { + t.Fatalf("write %s: %v", name, err) + } + } + return path +} + +func TestSeekMoonScanFindsOnlyTranscripts(t *testing.T) { + ws := t.TempDir() + path := writeSeekMoonSession(t, ws, "desktop-1", `{"version":1,"id":"desktop-1"}`+"\n") + + items, err := NewSeekMoonScanner().Scan([]string{filepath.Join(ws, ".openseek", "sessions")}) + if err != nil { + t.Fatalf("Scan: %v", err) + } + if len(items) != 1 { + t.Fatalf("want 1 item, got %d: %+v", len(items), items) + } + item := items[0] + if item.Platform != PlatformSeekMoon { + t.Errorf("platform = %q", item.Platform) + } + if item.Path != path { + t.Errorf("path = %q, want %q", item.Path, path) + } + if item.Status != "ready" { + t.Errorf("status = %q, want ready", item.Status) + } + if item.SizeBytes == 0 { + t.Error("SizeBytes not set") + } + + // A missing root is not an error. + missing, err := NewSeekMoonScanner().Scan([]string{filepath.Join(ws, "nope")}) + if err != nil { + t.Fatalf("Scan(missing): %v", err) + } + if len(missing) != 0 { + t.Errorf("want no items for a missing root, got %d", len(missing)) + } +} + +func TestSeekMoonReadMapsRecords(t *testing.T) { + path := filepath.Join("testdata", "seekmoon_sample.jsonl") + conv, err := NewSeekMoonScanner().Read(Item{Platform: PlatformSeekMoon, Path: path}) + if err != nil { + t.Fatalf("Read: %v", err) + } + if len(conv.Messages) != 3 { + t.Fatalf("want 3 messages (user, assistant, tool), got %d: %+v", len(conv.Messages), conv.Messages) + } + + user := conv.Messages[0] + if user.Role != "user" || user.Content != "how do I ship a release?" { + t.Errorf("user message = %+v", user) + } + if user.Timestamp != 1767225600000 { + t.Errorf("user ts = %d", user.Timestamp) + } + + assistant := conv.Messages[1] + if assistant.Role != "assistant" || assistant.Content != "Tag it, then push the tag." { + t.Errorf("assistant message = %+v", assistant) + } + if len(assistant.ToolCalls) != 1 { + t.Fatalf("want 1 tool call, got %d", len(assistant.ToolCalls)) + } + call := assistant.ToolCalls[0] + if call.ID != "call_00_tag" || call.Name != "shell" || call.Type != "function" { + t.Errorf("tool call = %+v", call) + } + if !strings.Contains(call.Arguments, "git tag v1.0.0") { + t.Errorf("tool arguments = %q", call.Arguments) + } + + tool := conv.Messages[2] + if tool.Role != "tool" || tool.ToolCallID != "call_00_tag" || tool.Content != "tagged" { + t.Errorf("tool result = %+v", tool) + } + + // runtime_notice and terminal are app bookkeeping, not conversation. + for _, m := range conv.Messages { + if s, ok := m.Content.(string); ok && strings.Contains(s, "background job finished") { + t.Errorf("runtime_notice leaked into the conversation: %+v", m) + } + } + + // The id comes from the header, so re-imports address the same session. + want := ConversationID(PlatformSeekMoon, "desktop-20260101-000000-000-000000001", path) + if conv.ID != want { + t.Errorf("conversation id = %q, want %q", conv.ID, want) + } + if !strings.HasPrefix(conv.ID, "import-seekmoon-desktop-20260101") { + t.Errorf("conversation id = %q", conv.ID) + } + if conv.Item.StartedAt == "" { + t.Error("StartedAt not set from messages") + } +} + +func TestSeekMoonReadToleratesJunk(t *testing.T) { + body := strings.Join([]string{ + `{"version":1,"id":"desktop-2"}`, + `not json at all`, + `{"sequence":1,"ts":1767225600000,"item":{"kind":"user","payload":{"content":"hi"}}}`, + `{"sequence":2,"ts":1767225601000,"item":{"kind":"mystery","payload":{}}}`, + `{"sequence":3,"ts":1767225602000,"item":{"kind":"tool_result","payload":{"content":"orphan"}}}`, + `{"sequence":4,"ts":1767225603000,"item":{"kind":"assistant","payload":{"content":"","reasoning_content":"only thinking"}}}`, + }, "\n") + path := filepath.Join(t.TempDir(), "openseek_session-desktop-2.jsonl") + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatalf("write: %v", err) + } + + conv, err := NewSeekMoonScanner().Read(Item{Platform: PlatformSeekMoon, Path: path}) + if err != nil { + t.Fatalf("Read must tolerate junk: %v", err) + } + if len(conv.Messages) != 1 || conv.Messages[0].Content != "hi" { + t.Fatalf("want only the user message, got %+v", conv.Messages) + } + if len(conv.Warnings) != 3 { + t.Fatalf("want 3 warnings (bad json, unknown kind, orphan tool_result), got %d: %v", len(conv.Warnings), conv.Warnings) + } + joined := strings.Join(conv.Warnings, "\n") + for _, want := range []string{"json decode error", "unknown record kind", "missing tool_call_id"} { + if !strings.Contains(joined, want) { + t.Errorf("warnings missing %q: %v", want, conv.Warnings) + } + } +} + +func TestSeekMoonDefaultRootsUseWorkspaceRegistry(t *testing.T) { + homeDir := t.TempDir() + registry := `{"workspaces":["/ws/one","/ws/two"],"initialized":true}` + if err := os.WriteFile(filepath.Join(homeDir, "workspaces.json"), []byte(registry), 0o600); err != nil { + t.Fatalf("write registry: %v", err) + } + t.Setenv("EVERCLI_SEEKMOON_HOME", homeDir) + t.Setenv("EVERCLI_SEEKMOON_WORKSPACES", "") + + roots := DefaultRoots(PlatformSeekMoon) + want := []string{ + filepath.Join("/ws/one", ".openseek", "sessions"), + filepath.Join("/ws/two", ".openseek", "sessions"), + } + if len(roots) != len(want) { + t.Fatalf("roots = %v, want %v", roots, want) + } + for i := range want { + if roots[i] != want[i] { + t.Errorf("roots[%d] = %q, want %q", i, roots[i], want[i]) + } + } + + // The env override wins, which is what tests and unusual layouts use. + t.Setenv("EVERCLI_SEEKMOON_WORKSPACES", strings.Join([]string{"/ws/three", "/ws/four"}, string(os.PathListSeparator))) + roots = DefaultRoots(PlatformSeekMoon) + if len(roots) != 2 || roots[0] != filepath.Join("/ws/three", ".openseek", "sessions") { + t.Errorf("override roots = %v", roots) + } +} + +func TestResolveSeekMoonEvt(t *testing.T) { + t.Run("reads the token from the mcp entry", func(t *testing.T) { + runtimeDir := t.TempDir() + t.Setenv("EVERCLI_SEEKMOON_CONFIG_DIR", runtimeDir) + cfg := `{"mcpServers":{ + "seekmoon":{"url":"http://127.0.0.1:1/mcp"}, + "everme-memory":{"command":"npx","args":["-y","@everme/memory-mcp@latest"], + "env":{"EVERME_API_BASE":"https://api.test","EVERME_AGENT_ID":"agt_x","EVERME_AGENT_TOKEN":" evt_test "}}}}` + if err := os.WriteFile(filepath.Join(runtimeDir, "host-mcp.json"), []byte(cfg), 0o600); err != nil { + t.Fatalf("write config: %v", err) + } + + tok, err := ResolveEvt(PlatformSeekMoon) + if err != nil { + t.Fatalf("ResolveEvt: %v", err) + } + if tok != "evt_test" { + t.Errorf("token = %q (must be trimmed)", tok) + } + }) + + t.Run("missing entry explains how to get one", func(t *testing.T) { + runtimeDir := t.TempDir() + t.Setenv("EVERCLI_SEEKMOON_CONFIG_DIR", runtimeDir) + cfg := `{"mcpServers":{"seekmoon":{"url":"http://127.0.0.1:1/mcp"}}}` + if err := os.WriteFile(filepath.Join(runtimeDir, "host-mcp.json"), []byte(cfg), 0o600); err != nil { + t.Fatalf("write config: %v", err) + } + + _, err := ResolveEvt(PlatformSeekMoon) + if err == nil { + t.Fatal("want an error when the everme-memory entry is missing") + } + for _, want := range []string{"evercli plugin install seekmoon", "EVERME_AGENT_TOKEN", "host-mcp.json"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("error %q must mention %q", err.Error(), want) + } + } + }) + + t.Run("empty token is reported", func(t *testing.T) { + runtimeDir := t.TempDir() + t.Setenv("EVERCLI_SEEKMOON_CONFIG_DIR", runtimeDir) + cfg := `{"mcpServers":{"everme-memory":{"env":{"EVERME_AGENT_TOKEN":" "}}}}` + if err := os.WriteFile(filepath.Join(runtimeDir, "host-mcp.json"), []byte(cfg), 0o600); err != nil { + t.Fatalf("write config: %v", err) + } + + _, err := ResolveEvt(PlatformSeekMoon) + if err == nil || !strings.Contains(err.Error(), "EVERME_AGENT_TOKEN is empty") { + t.Fatalf("want an empty-token error, got %v", err) + } + }) +} + +// The platform must be discoverable by the CLI and by the default registry, +// otherwise `--platform seekmoon` is rejected before any scan happens. +func TestSeekMoonPlatformIsRegistered(t *testing.T) { + if !IsKnownPlatform(PlatformSeekMoon) { + t.Error("seekmoon is not a known platform") + } + if !strings.Contains(PlatformList(), "seekmoon") { + t.Errorf("PlatformList() = %q", PlatformList()) + } + if ids, err := ParsePlatforms([]string{"seekmoon"}); err != nil || len(ids) != 1 || ids[0] != PlatformSeekMoon { + t.Errorf("ParsePlatforms(seekmoon) = %v, %v", ids, err) + } + if DefaultRegistry().ScannerFor(PlatformSeekMoon) == nil { + t.Error("DefaultRegistry has no seekmoon scanner") + } + // A scan of an unknown platform still fails with the full list. + if _, err := ParsePlatforms([]string{"nope"}); err == nil { + t.Error("unknown platform must be rejected") + } else if !strings.Contains(err.Error(), "seekmoon") { + t.Errorf("rejection message must list the platforms: %v", err) + } + // Sanity: the fixture parses as JSON, so a broken testdata file fails here + // rather than as a mysterious warning during Read. + raw, err := os.ReadFile(filepath.Join("testdata", "seekmoon_sample.jsonl")) + if err != nil { + t.Fatalf("read fixture: %v", err) + } + for i, line := range strings.Split(strings.TrimSpace(string(raw)), "\n") { + var v any + if err := json.Unmarshal([]byte(line), &v); err != nil { + t.Errorf("fixture line %d is not JSON: %v", i+1, err) + } + } +} diff --git a/cli/internal/importer/conversation/testdata/seekmoon_sample.jsonl b/cli/internal/importer/conversation/testdata/seekmoon_sample.jsonl new file mode 100644 index 0000000..7fc5df3 --- /dev/null +++ b/cli/internal/importer/conversation/testdata/seekmoon_sample.jsonl @@ -0,0 +1,6 @@ +{"version":1,"id":"desktop-20260101-000000-000-000000001","system_prompt":"You are an agent focused on implementing user tasks."} +{"sequence":1,"ts":1767225600000,"item":{"kind":"user","payload":{"content":"how do I ship a release?","submission_id":"desktop-20260101-000000-000-000000001-submission-1"}}} +{"sequence":2,"ts":1767225601000,"item":{"kind":"assistant","payload":{"content":"Tag it, then push the tag.","tool_calls":[{"id":"call_00_tag","name":"shell","arguments":"{\"cmd\":\"git tag v1.0.0\"}"}],"reasoning_content":"the user wants the release flow","usage":{"prompt_tokens":10,"completion_tokens":5}}}} +{"sequence":3,"ts":1767225601200,"item":{"kind":"tool_result","payload":{"tool_call_id":"call_00_tag","tool_name":"shell","content":"tagged","is_error":false,"brief":"tag v1.0.0"}}} +{"sequence":4,"ts":1767225601500,"item":{"kind":"runtime_notice","payload":{"content":"background job finished (exit=0)"}}} +{"sequence":5,"ts":1767225602000,"item":{"kind":"terminal","payload":{"kind":"finished","message":"done"}}} diff --git a/cli/internal/importer/conversation/types.go b/cli/internal/importer/conversation/types.go index 0b452f7..04cd568 100644 --- a/cli/internal/importer/conversation/types.go +++ b/cli/internal/importer/conversation/types.go @@ -13,6 +13,7 @@ const ( PlatformKimicode PlatformID = "kimicode" PlatformRaven PlatformID = "raven" PlatformWorkBuddy PlatformID = "workbuddy" + PlatformSeekMoon PlatformID = "seekmoon" ) // AgentMemoryToolCall mirrors the BFF /mem/agent-memory camelCase DTO.