i-self 0.4.3

Personal developer-companion CLI: scans your repos, indexes code semantically, watches your activity, and moves AI-agent sessions between tools (Claude Code, Aider, Goose, OpenAI Codex CLI, Continue.dev, OpenCode).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Cross-agent session import.
//!
//! Read a session that someone else exported (JSON, the canonical interchange
//! format) and write it into another tool's on-disk format so the recipient
//! can continue the conversation in *their* preferred agent.
//!
//! Design notes:
//!
//! - **JSON is the only portable input.** Our Markdown render is for humans;
//!   parsing it back is brittle (markdown-in-markdown, escaped backticks,
//!   etc.). Always go through `share export --format json` for handoffs.
//!
//! - **Fidelity is best-effort.** Tool-call structure flattens to text when
//!   crossing agents; thinking blocks render as plain prose. The recipient
//!   gets a faithful transcript they can read and continue from, not a
//!   "live" session that's wire-compatible with the source agent.
//!
//! - **Some targets aren't file-addressable.** Copilot Chat, Cline, Cursor
//!   store sessions in editor-globalState / IndexedDB. For those, the
//!   `clipboard` target emits a Markdown blob the user pastes into the
//!   agent's chat box. (We don't write to the OS clipboard ourselves —
//!   pipe to `pbcopy` / `xclip` / `Set-Clipboard`.)

use super::{render, SessionMessage, MessageRole, ShareError, SharedSession};
use anyhow::Result;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Default)]
pub struct ImportOptions {
    /// Aider needs a target project directory because its history lives at
    /// `<project>/.aider.chat.history.md`. Claude Code uses this as the
    /// session's `cwd` if provided; otherwise inherits the source session's.
    pub project_path: Option<PathBuf>,
    /// Per-target root directory override. Each importer interprets this in
    /// its own way:
    ///
    /// - `claude-code`: replaces `~/.claude/projects/`
    /// - `goose`:       replaces `~/.config/goose/sessions/`
    /// - `codex`:       replaces `~/.codex/sessions/`
    /// - `continue`:    replaces `~/.continue/sessions/`
    ///
    /// Aider ignores this — `project_path` is its analog. The clipboard
    /// importer ignores both. Mostly useful for tests; production code
    /// usually leaves it `None` and lets each importer use its env-var or
    /// platform default.
    pub dest_root_override: Option<PathBuf>,
}

pub trait SessionImporter: Send + Sync {
    fn name(&self) -> &str;
    /// Write the session in this target's native format. Returns a
    /// human-readable description of what was written (typically a path).
    fn import(&self, session: &SharedSession, opts: &ImportOptions) -> Result<String, ShareError>;
}

pub fn importers() -> Vec<Box<dyn SessionImporter>> {
    vec![
        Box::new(ClaudeCodeImporter::default()),
        Box::new(AiderImporter::default()),
        Box::new(super::goose::GooseImporter::default()),
        Box::new(super::codex::CodexImporter::default()),
        Box::new(super::continue_dev::ContinueImporter::default()),
        Box::new(super::generic_openai::GenericOpenAIImporter::default()),
        Box::new(ClipboardImporter::default()),
    ]
}

pub fn find_importer(name: &str) -> Option<Box<dyn SessionImporter>> {
    importers().into_iter().find(|i| i.name() == name)
}

/// Load a session for import. Accepts:
/// - `"-"` for stdin
/// - `http://...` / `https://...` for a presigned URL or any HTTP source
/// - any other string → treated as a filesystem path
///
/// Input must be JSON. Markdown is intentionally rejected — see module docs.
pub async fn load_shared(input: &str) -> Result<SharedSession, ShareError> {
    let raw = if input == "-" {
        use std::io::Read;
        let mut s = String::new();
        std::io::stdin()
            .read_to_string(&mut s)
            .map_err(ShareError::Io)?;
        s
    } else if input.starts_with("http://") || input.starts_with("https://") {
        let resp = reqwest::get(input)
            .await
            .map_err(|e| ShareError::Parse(format!("fetch {}: {}", input, e)))?;
        let status = resp.status();
        if !status.is_success() {
            return Err(ShareError::Parse(format!(
                "fetch {}: HTTP {}",
                input, status
            )));
        }
        resp.text()
            .await
            .map_err(|e| ShareError::Parse(format!("read body: {}", e)))?
    } else {
        std::fs::read_to_string(input).map_err(ShareError::Io)?
    };

    serde_json::from_str(&raw).map_err(|e| {
        ShareError::Parse(format!(
            "input is not valid JSON ({}). Use `share export --format json` to produce a portable file.",
            e
        ))
    })
}

// ---------------------------------------------------------------------------
// Claude Code importer
// ---------------------------------------------------------------------------

#[derive(Default)]
pub struct ClaudeCodeImporter;

impl SessionImporter for ClaudeCodeImporter {
    fn name(&self) -> &str {
        "claude-code"
    }

    fn import(&self, session: &SharedSession, opts: &ImportOptions) -> Result<String, ShareError> {
        let root = opts
            .dest_root_override
            .clone()
            .or_else(|| dirs::home_dir().map(|h| h.join(".claude").join("projects")))
            .ok_or_else(|| ShareError::Parse("no home directory".into()))?;

        // Pick a target cwd — explicit override > source session's cwd >
        // current process cwd. The directory name uses Claude Code's encoding
        // (non-alnum → `-`).
        let cwd = opts
            .project_path
            .clone()
            .or_else(|| session.project_path.clone())
            .or_else(|| std::env::current_dir().ok())
            .ok_or_else(|| ShareError::Parse("could not determine target cwd".into()))?;

        let dir_name = encode_claude_project_dir(&cwd);
        let project_dir = root.join(dir_name);
        std::fs::create_dir_all(&project_dir).map_err(ShareError::Io)?;

        let new_session_id = uuid::Uuid::new_v4().to_string();
        let file_path = project_dir.join(format!("{}.jsonl", new_session_id));

        // Build the JSONL. Each message becomes one envelope. A leading
        // synthetic user message records the import provenance so the
        // recipient knows where the transcript came from — not just text in
        // the conversation but `metadata.imported_from` they can grep for.
        let mut out = String::new();
        let now = chrono::Utc::now().to_rfc3339();
        let provenance = serde_json::json!({
            "type": "user",
            "message": {
                "role": "user",
                "content": format!(
                    "[i-self import] Continued from {} session {}. {} prior messages follow.",
                    session.provider,
                    session.id,
                    session.messages.len()
                )
            },
            "uuid": uuid::Uuid::new_v4().to_string(),
            "sessionId": new_session_id,
            "timestamp": now,
            "cwd": cwd.to_string_lossy(),
            "imported_from": {
                "provider": session.provider,
                "id": session.id,
            }
        });
        out.push_str(&provenance.to_string());
        out.push('\n');

        for msg in &session.messages {
            let envelope = encode_envelope(msg, &cwd, &new_session_id);
            out.push_str(&envelope.to_string());
            out.push('\n');
        }

        std::fs::write(&file_path, out).map_err(ShareError::Io)?;
        Ok(format!(
            "Wrote {} messages to {} (session {}). Run `claude` from {} and pick this session.",
            session.messages.len() + 1,
            file_path.display(),
            new_session_id,
            cwd.display()
        ))
    }
}

/// Claude Code encodes the cwd as the dir name with every non-alphanumeric
/// (and non-`/`) char becoming `-`, then `/` → `-`. We mirror that.
fn encode_claude_project_dir(p: &Path) -> String {
    let s = p.to_string_lossy();
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        if ch.is_ascii_alphanumeric() {
            out.push(ch);
        } else {
            out.push('-');
        }
    }
    out
}

fn encode_envelope(msg: &SessionMessage, cwd: &Path, session_id: &str) -> serde_json::Value {
    let timestamp = msg
        .timestamp
        .map(|t| t.to_rfc3339())
        .unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
    let uuid = uuid::Uuid::new_v4().to_string();

    match msg.role {
        MessageRole::User | MessageRole::ToolResult => serde_json::json!({
            "type": "user",
            "message": {"role": "user", "content": msg.content},
            "uuid": uuid,
            "sessionId": session_id,
            "timestamp": timestamp,
            "cwd": cwd.to_string_lossy(),
        }),
        MessageRole::Assistant | MessageRole::System | MessageRole::ToolUse => {
            let model = msg
                .metadata
                .get("model")
                .cloned()
                .unwrap_or_else(|| "imported".to_string());
            let mut content = vec![serde_json::json!({"type": "text", "text": &msg.content})];
            // ToolUse messages get an extra block flagged as such, so a
            // future viewer can distinguish them from plain assistant text.
            if msg.role == MessageRole::ToolUse {
                if let Some(name) = msg.metadata.get("tool_name") {
                    content.insert(
                        0,
                        serde_json::json!({
                            "type": "imported_tool_use",
                            "name": name,
                            "summary": &msg.content,
                        }),
                    );
                }
            }
            serde_json::json!({
                "type": "assistant",
                "message": {
                    "role": "assistant",
                    "model": model,
                    "content": content,
                },
                "uuid": uuid,
                "sessionId": session_id,
                "timestamp": timestamp,
            })
        }
    }
}

// ---------------------------------------------------------------------------
// Aider importer
// ---------------------------------------------------------------------------

#[derive(Default)]
pub struct AiderImporter;

impl SessionImporter for AiderImporter {
    fn name(&self) -> &str {
        "aider"
    }

    fn import(&self, session: &SharedSession, opts: &ImportOptions) -> Result<String, ShareError> {
        // Aider needs a project dir. If neither the option nor the source
        // session has one, fall back to current dir.
        let project = opts
            .project_path
            .clone()
            .or_else(|| session.project_path.clone())
            .or_else(|| std::env::current_dir().ok())
            .ok_or_else(|| ShareError::Parse("could not determine project path".into()))?;

        std::fs::create_dir_all(&project).map_err(ShareError::Io)?;
        let history = project.join(".aider.chat.history.md");

        let mut buf = String::new();
        // Aider's normal session header — it'll show this as a discrete
        // chat in `aider --history`.
        buf.push_str(&format!(
            "\n# aider chat started at {}\n\n",
            chrono::Local::now().format("%Y-%m-%d %H:%M:%S")
        ));
        buf.push_str(&format!(
            "> [i-self import] Continued from {} session {}. {} prior messages follow.\n\n",
            session.provider,
            session.id,
            session.messages.len()
        ));

        for msg in &session.messages {
            match msg.role {
                MessageRole::User | MessageRole::ToolResult => {
                    for line in msg.content.lines() {
                        buf.push_str("> ");
                        buf.push_str(line);
                        buf.push('\n');
                    }
                    buf.push('\n');
                }
                MessageRole::Assistant | MessageRole::System => {
                    buf.push_str(&msg.content);
                    if !msg.content.ends_with('\n') {
                        buf.push('\n');
                    }
                    buf.push('\n');
                }
                MessageRole::ToolUse => {
                    // Render tool calls as fenced blocks in the assistant slot
                    // so they read sensibly when scrolling the history.
                    let name = msg
                        .metadata
                        .get("tool_name")
                        .map(|s| s.as_str())
                        .unwrap_or("tool");
                    buf.push_str(&format!("```{}\n{}\n```\n\n", name, msg.content));
                }
            }
        }

        // Open existing file in append mode (or create) — never truncate, so
        // multiple imports stack.
        use std::fs::OpenOptions;
        use std::io::Write;
        let mut f = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&history)
            .map_err(ShareError::Io)?;
        f.write_all(buf.as_bytes()).map_err(ShareError::Io)?;

        Ok(format!(
            "Appended {} messages to {}. Run `aider --restore-chat-history` from {} to continue.",
            session.messages.len(),
            history.display(),
            project.display()
        ))
    }
}

// ---------------------------------------------------------------------------
// Clipboard importer
// ---------------------------------------------------------------------------

/// "Import" target for tools that don't expose addressable session storage —
/// Copilot Chat, Cline, Cursor. Renders the session as Markdown to stdout
/// so the user can `| pbcopy` (macOS), `| xclip -selection clipboard` (X11),
/// or `| Set-Clipboard` (PowerShell) and paste into the chat box.
#[derive(Default)]
pub struct ClipboardImporter;

impl SessionImporter for ClipboardImporter {
    fn name(&self) -> &str {
        "clipboard"
    }

    fn import(&self, session: &SharedSession, _opts: &ImportOptions) -> Result<String, ShareError> {
        let md = render::render(session, render::RenderFormat::Markdown)
            .map_err(|e| ShareError::Parse(format!("render: {}", e)))?;
        // The CLI writes this to stdout; the importer trait returns a status
        // string for the user. Pipe to your platform's clipboard tool.
        print!("{}", md);
        Ok(format!(
            "Wrote {} messages as Markdown to stdout. Pipe to `pbcopy` / `xclip -selection clipboard` / `Set-Clipboard` and paste into your agent.",
            session.messages.len()
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    fn fixture() -> SharedSession {
        SharedSession {
            provider: "claude-code".into(),
            id: "src-session".into(),
            project_path: Some(PathBuf::from("/Users/foo/proj")),
            started_at: Some(chrono::Utc::now()),
            messages: vec![
                SessionMessage {
                    role: MessageRole::User,
                    content: "fix the auth bug".into(),
                    timestamp: None,
                    metadata: HashMap::new(),
                },
                SessionMessage {
                    role: MessageRole::Assistant,
                    content: "Looking at auth.rs…".into(),
                    timestamp: None,
                    metadata: HashMap::from([("model".into(), "claude".into())]),
                },
                SessionMessage {
                    role: MessageRole::ToolUse,
                    content: "Read({\"path\":\"src/auth.rs\"})".into(),
                    timestamp: None,
                    metadata: HashMap::from([("tool_name".into(), "Read".into())]),
                },
            ],
        }
    }

    #[test]
    fn claude_code_importer_writes_jsonl_with_provenance() {
        let tmp = tempfile::tempdir().unwrap();
        let opts = ImportOptions {
            project_path: Some(PathBuf::from("/test/dir")),
            dest_root_override: Some(tmp.path().to_path_buf()),
        };
        let importer = ClaudeCodeImporter;
        importer.import(&fixture(), &opts).unwrap();

        let project_dirs: Vec<_> = std::fs::read_dir(tmp.path()).unwrap().collect();
        assert_eq!(project_dirs.len(), 1);

        let project_dir = project_dirs.into_iter().next().unwrap().unwrap().path();
        // Encoded "/test/dir" → "-test-dir" (slash + dot become hyphens via
        // ASCII-alnum check).
        assert!(project_dir.file_name().unwrap().to_str().unwrap().starts_with('-'));

        let jsonl_files: Vec<_> = std::fs::read_dir(&project_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().map(|x| x == "jsonl").unwrap_or(false))
            .collect();
        assert_eq!(jsonl_files.len(), 1);

        let content = std::fs::read_to_string(jsonl_files[0].path()).unwrap();
        // 1 provenance + 3 fixture messages = 4 lines
        assert_eq!(content.lines().count(), 4);
        assert!(content.contains("[i-self import]"));
        assert!(content.contains("imported_from"));
        assert!(content.contains("\"role\":\"user\""));
        assert!(content.contains("\"role\":\"assistant\""));
    }

    #[test]
    fn aider_importer_appends_session_to_history() {
        let tmp = tempfile::tempdir().unwrap();
        let opts = ImportOptions {
            project_path: Some(tmp.path().to_path_buf()),
            ..ImportOptions::default()
        };
        let importer = AiderImporter;
        importer.import(&fixture(), &opts).unwrap();

        let history = tmp.path().join(".aider.chat.history.md");
        let content = std::fs::read_to_string(&history).unwrap();
        assert!(content.contains("# aider chat started at"));
        assert!(content.contains("[i-self import]"));
        assert!(content.contains("> fix the auth bug"));
        assert!(content.contains("Looking at auth.rs"));
        // Tool use rendered as fenced block
        assert!(content.contains("```Read"));
    }

    #[test]
    fn aider_importer_appends_rather_than_overwrites() {
        let tmp = tempfile::tempdir().unwrap();
        let opts = ImportOptions {
            project_path: Some(tmp.path().to_path_buf()),
            ..ImportOptions::default()
        };
        // Pre-existing history.
        std::fs::write(
            tmp.path().join(".aider.chat.history.md"),
            "# aider chat started at 2026-01-01 00:00:00\n\n> earlier work\n\nyes\n",
        )
        .unwrap();

        AiderImporter.import(&fixture(), &opts).unwrap();
        let content =
            std::fs::read_to_string(tmp.path().join(".aider.chat.history.md")).unwrap();
        assert!(content.contains("earlier work"), "preserves prior content");
        assert!(content.contains("[i-self import]"), "adds new content");
    }

    #[test]
    fn find_importer_returns_known_targets() {
        assert!(find_importer("claude-code").is_some());
        assert!(find_importer("aider").is_some());
        assert!(find_importer("clipboard").is_some());
        assert!(find_importer("nope").is_none());
    }

    #[tokio::test]
    async fn load_shared_reads_local_json() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("session.json");
        std::fs::write(&path, serde_json::to_string(&fixture()).unwrap()).unwrap();
        let s = load_shared(path.to_str().unwrap()).await.unwrap();
        assert_eq!(s.id, "src-session");
        assert_eq!(s.messages.len(), 3);
    }

    #[tokio::test]
    async fn load_shared_rejects_markdown() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("session.md");
        std::fs::write(&path, "# header\n\nnot json").unwrap();
        let err = load_shared(path.to_str().unwrap()).await.unwrap_err();
        assert!(matches!(err, ShareError::Parse(_)));
    }
}