Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

import: continue Claude Code conversations in graff (ADR 0254)

justrach1d517770b400
diff --git a/README.md b/README.md
index 9e831e4e..9ce6c4b2 100644
--- a/README.md
+++ b/README.md
@@ -192,6 +192,15 @@ or pass `--yolo`. Full flag list: `graff --help`. Learning:
A bare `/` opens a filterable menu, Esc interrupts the turn, and `/help` is the
live catalog.
+`/import-claude` (or `graff mcp import`) also imports the current project's
+Claude Code conversations for `/resume`. Imports keep text, tool calls and
+results, titles, timestamps, and the Claude model; signed thinking and subagent
+sidechains are omitted. Saves use `claude-<session-id>` names, and repeat imports
+leave existing saves intact. Resuming uses the currently configured graff provider
+and its credentials; Claude Code subscription credits are never used. The source
+model remains historical metadata. Import one conversation without copying setup
+with `graff mcp import-session <Claude-session-id>`.
+
| mode | what it does |
| --- | --- |
| default | ask before writes, MCP, and non-read-only bash |
diff --git a/docs/adr/0254-imported-conversations-use-the-configured-route.md b/docs/adr/0254-imported-conversations-use-the-configured-route.md
new file mode 100644
index 00000000..48db88cf
--- /dev/null
+++ b/docs/adr/0254-imported-conversations-use-the-configured-route.md
@@ -0,0 +1,24 @@
+# 0254. Imported conversations use the configured route
+
+Status: accepted 2026-10-04
+
+## Context
+
+An imported transcript records the source model, but restoring that route would
+require unrelated credentials and override the user's configured agent.
+
+## Decision
+
+Claude transcript imports carry `imported_from: "claude"`. Their first load keeps
+the configured graff provider and credentials. Source model fields are historical
+metadata; import never launches or authenticates the source runtime.
+
+When the wire format changes, historical tool calls and results become labeled
+text receipts. Ordinary graff saves retain their existing route-restoration rule.
+After continuation, the imported session is saved as an ordinary graff session.
+
+## Evidence
+
+[Import regression tests](../../src/adopt_sessions_tests.zig) cover empty source
+credentials and retained tool results across request formats. The
+`claude-conversation-import-resume` behavior case checks the model request.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 07937ac0..ac864fdf 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -279,6 +279,7 @@ record only when you need the evidence or the edge cases.
| [0250](0250-pr-publication-is-not-gated.md) | PR publication is not gated: no local-check, head-CI or claim-review preflight and no completion obligation; drafts complete like any task. Artifact claims and disclosure policy are unchanged. Supersedes 0120, 0123, 0126, 0133 and parts of 0100/0104. |
| [0251](0251-tool-results-inline-up-to-64-kib.md) | Tool results inline up to 64 KiB (was 16 KiB); `effectiveThreshold` still clamps to half the context window, so small windows are unchanged. The codedb small-read exemption follows the same number. |
| [0253](0253-an-interactive-session-signs-in-to-chatgpt-again.md) | When a ChatGPT request is rejected and the refresh cannot replace the token, an interactive root session opens the browser sign-in, waits up to three minutes and retries once; `-p`, piped, `--json`, ACP and sub-agents never do. One unfinished sign-in ends it for the process. |
+| [0254](0254-imported-conversations-use-the-configured-route.md) | Imported Claude history uses the configured graff provider and credentials; source models are metadata, and foreign tool results remain historical receipts. |
## When to write one
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index 48e62964..3272e75f 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -132,3 +132,4 @@
{"id": "headless-waits-for-background-job", "why": "Run until idle: a --json turn that ends while its background job runs waits for the job and continues with its result, instead of ending with the result lost.", "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Start the background build, then report its result.", "script": [{"tool": "bash", "arguments": {"command": "sleep 0.5; echo BUILD_RESULT_READY", "run_in_background": true}}, {"text": "The build is running in the background; I will report when it finishes."}, {"text": "The build finished and printed BUILD_RESULT_READY."}], "assert": [{"request_count": 3}, {"request_contains": {"index": 2, "text": "BUILD_RESULT_READY"}}, {"events_at_most": {"match": {"type": "turn"}, "count": 1}}, {"final_text_contains": "The build finished and printed BUILD_RESULT_READY."}]}
{"id": "headless-heartbeat-checks-stuck-job", "why": "Run until idle: a waiting run wakes the model with a heartbeat after silence, naming the running job, so it can stop work that will not finish.", "env": {"GRAFF_NO_CODEDB_GUARD": "1", "GRAFF_HEARTBEAT_SECS": "1"}, "prompt": "Start the background watcher and handle it.", "script": [{"tool": "bash", "arguments": {"command": "sleep 30; echo NEVER_PRINTED", "run_in_background": true}}, {"text": "The watcher is running."}, {"tool": "bash_kill", "arguments": {"id": 4294967296}}, {"text": "Stopped the watcher; it was not going to finish."}], "assert": [{"request_count": 4}, {"request_contains": {"index": 2, "text": "[heartbeat: no news from background work"}}, {"request_contains": {"index": 2, "text": "sleep 30"}}, {"final_text_contains": "Stopped the watcher"}], "workspace_seed": {".codegraff/shell-id.lock": "shell-ids-v1\n", ".codegraff/shell-id.counter": "4294967295\n"}}
{"id": "headless-server-does-not-hold", "why": "Run until idle: a server never reports, so a turn that leaves one running in the background ends instead of waiting on it.", "env": {"GRAFF_NO_CODEDB_GUARD": "1", "GRAFF_HEARTBEAT_SECS": "1"}, "prompt": "Start the dev server in the background and confirm it launched.", "script": [{"tool": "bash", "arguments": {"command": "python3 -m http.server 0 --bind 127.0.0.1", "run_in_background": true}}, {"text": "The dev server is running."}], "assert": [{"request_count": 2}, {"final_text_contains": "The dev server is running."}]}
+{"id": "claude-conversation-import-resume", "why": "Imported history uses the configured graff route without Claude credentials, retaining dialogue and historical tool results.", "env": {"ANTHROPIC_API_KEY": ""}, "args": ["--resume", "claude-import-fixture"], "claude_transcripts": {"import-fixture.jsonl": "{\"type\": \"user\", \"uuid\": \"u1\", \"message\": {\"content\": \"import-retained-question-1495\"}}\n{\"type\": \"assistant\", \"uuid\": \"a1\", \"message\": {\"model\": \"claude-sonnet-4-5\", \"content\": [{\"type\": \"thinking\", \"thinking\": \"import-private-thinking-1495\", \"signature\": \"signed\"}, {\"type\": \"text\", \"text\": \"import-retained-answer-1495\"}, {\"type\": \"tool_use\", \"id\": \"tool-import-1495\", \"name\": \"Bash\", \"input\": {\"command\": \"echo imported\"}}]}}\n{\"type\": \"user\", \"message\": {\"content\": [{\"type\": \"tool_result\", \"tool_use_id\": \"tool-import-1495\", \"content\": \"import-retained-result-1495\"}]}}\n{\"type\": \"assistant\", \"isSidechain\": true, \"message\": {\"content\": [{\"type\": \"text\", \"text\": \"import-sidechain-1495\"}]}}\n{\"type\": \"assistant\", \"message\": {\"content\": [{\"type\": \"text\", \"text\": \"import-finished-1495\"}]}}\n"}, "controls_before_prompt": [{"type": "set_model", "provider": "lmstudio", "model": "mock"}], "prompt": "Continue the imported task.", "script": [{"text": "Imported history is available."}], "assert": [{"request_contains": {"index": 0, "text": "import-retained-question-1495"}}, {"request_contains": {"index": 0, "text": "import-retained-answer-1495"}}, {"request_contains": {"index": 0, "text": "import-retained-result-1495"}}, {"request_contains": {"index": 0, "text": "import-finished-1495"}}, {"request_lacks": {"index": 0, "text": "import-private-thinking-1495"}}, {"request_lacks": {"index": 0, "text": "import-sidechain-1495"}}, {"final_text_contains": "Imported history is available."}]}
diff --git a/scripts/eval-tier2.py b/scripts/eval-tier2.py
index feec90c9..732110e0 100644
--- a/scripts/eval-tier2.py
+++ b/scripts/eval-tier2.py
@@ -53,6 +53,8 @@ files written into the fresh workspace BEFORE graff boots, in scripted and
trajectory archive bench_priors folds. Under --provider the ScriptedModel
never runs, so request_contains/request_lacks are skipped and scoring rests
on the event and final-text asserts.
+`claude_transcripts` seeds per-project Claude JSONL files and runs the explicit
+import command before startup, for conversation import/resume regressions.
"""
from __future__ import annotations
@@ -168,6 +170,15 @@ def execute(case: dict[str, Any], graff: str, port: int,
dest = pathlib.Path(workspace) / rel
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(content, encoding="utf-8")
+ if case.get("claude_transcripts"):
+ canonical = str(pathlib.Path(workspace).resolve())
+ slug = "".join(c if c.isascii() and c.isalnum() else "-" for c in canonical)
+ project = pathlib.Path(workspace) / ".claude" / "projects" / slug
+ project.mkdir(parents=True)
+ for name, content in case["claude_transcripts"].items():
+ (project / name).write_text(content, encoding="utf-8")
+ subprocess.run([graff, "mcp", "import"], cwd=workspace, env=env,
+ check=True, capture_output=True, text=True, timeout=30)
# Real linked-worktree topology for ownership/checkpoint cases.
if case.get("nested_worktree"):
for command in [
diff --git a/scripts/test-acp-session-load.py b/scripts/test-acp-session-load.py
index 82ca1f2a..244b654e 100644
--- a/scripts/test-acp-session-load.py
+++ b/scripts/test-acp-session-load.py
@@ -141,7 +141,71 @@ class FollowingModel(ScriptedModel):
return {"text": "done"}
+
+def claude_import(binary):
+ with tempfile.TemporaryDirectory(prefix="graff-acp-import-") as temporary:
+ cwd = Path(temporary).resolve()
+ home = cwd / "home"
+ config = home / ".claude"
+ slug = "".join(c if c.isascii() and c.isalnum() else "-" for c in str(cwd))
+ project = config / "projects" / slug
+ project.mkdir(parents=True)
+ records = [
+ {"type": "user", "message": {"content": "Imported human request."}},
+ {"type": "assistant", "message": {"model": "claude-source-model", "content": [
+ {"type": "thinking", "thinking": "private-import-thinking", "signature": "signed"},
+ {"type": "text", "text": "Imported assistant answer."},
+ {"type": "tool_use", "id": "import-call", "name": "Bash",
+ "input": {"command": "touch imported-tool-must-not-run"}},
+ ]}},
+ {"type": "user", "message": {"content": [
+ {"type": "tool_result", "tool_use_id": "import-call", "content": "Imported tool receipt."},
+ ]}},
+ ]
+ source = project / "chosen.jsonl"
+ original = "\n".join(json.dumps(record) for record in records) + "\n"
+ source.write_text(original)
+ (project / "other.jsonl").write_text(original)
+ env = dict(os.environ, HOME=str(home), CLAUDE_CONFIG_DIR=str(config), ANTHROPIC_API_KEY="")
+ env.pop("CLAUDE_CODE_PROJECT_DIR_NAME", None)
+ imported = subprocess.run([str(binary), "mcp", "import-session", "chosen"],
+ cwd=cwd, env=env, text=True, capture_output=True, timeout=15)
+ assert imported.returncode == 0, imported.stderr
+ assert imported.stdout.strip() == "claude-chosen", imported.stdout
+ assert not (cwd / ".graff/sessions/claude-other.session.json").exists()
+ model = ScriptedModel([{"text": "Continued through graff."}])
+ port = model.start(0)
+ client = Acp(binary, cwd, home, port, extra_env={"ANTHROPIC_API_KEY": ""})
+ try:
+ client.request("initialize", {"protocolVersion": 1})
+ client.request("session/new", {"cwd": str(cwd), "mcpServers": []})
+ loaded = client.request("session/load", {"sessionId": "claude-chosen", "cwd": str(cwd), "mcpServers": []})
+ assert "result" in loaded, loaded
+ reply = client.request("session/prompt", {"sessionId": "claude-chosen",
+ "prompt": [{"type": "text", "text": "Continue the imported task."}]})
+ assert reply["result"]["stopReason"] == "end_turn", reply
+ body = json.dumps(model.requests[0])
+ for text in ["Imported human request.", "Imported assistant answer.", "Imported tool receipt."]:
+ assert text in body, text
+ assert "private-import-thinking" not in body
+ assert model.requests[0]["model"] != "claude-source-model"
+ assert not (cwd / "imported-tool-must-not-run").exists()
+ assert source.read_text() == original
+ saved = cwd / ".graff/sessions/claude-chosen.session.json"
+ deadline = time.monotonic() + 5
+ while json.loads(saved.read_text()).get("provider") != "vercel" and time.monotonic() < deadline:
+ time.sleep(.05)
+ snapshot = json.loads(saved.read_text())
+ assert snapshot["provider"] == "vercel", snapshot
+ assert "imported_from" not in snapshot
+ finally:
+ client.close()
+ model.stop()
+ print("ACP Claude history import uses graff credentials and retains tool receipts: ok")
+
+
def run(binary):
+ claude_import(binary)
with tempfile.TemporaryDirectory(prefix="graff-acp-load-") as temporary:
cwd = Path(temporary)
home = cwd / "home"
diff --git a/src/adopt.zig b/src/adopt.zig
index 82503e95..48cd52ce 100644
--- a/src/adopt.zig
+++ b/src/adopt.zig
@@ -24,14 +24,22 @@ pub const Report = struct {
hooks: usize = 0,
rules: usize = 0,
sources: usize = 0,
+ sessions: usize = 0,
+ sessions_skipped: usize = 0,
+ sessions_failed: usize = 0,
};
/// `graff mcp import` / `graff import-claude`. Always allowed after first-run.
pub fn command(io: Io, arena: Allocator, home: []const u8, cwd: []const u8, out: *Io.Writer) !void {
- const r = try run(io, arena, home, cwd);
+ var r = try run(io, arena, home, cwd);
+ // Conversations are an explicit import, never part of first-run adoption.
+ const conversations = try @import("adopt_sessions.zig").run(io, arena, home, cwd);
+ r.sessions = conversations.imported;
+ r.sessions_skipped = conversations.skipped;
+ r.sessions_failed = conversations.failed;
markAdopted(io, arena, home);
- if (r.added_user + r.added_project + r.skills == 0 and r.skipped == 0) {
- try out.writeAll("nothing to adopt: no Claude/Cursor MCP servers or skills found.\n");
+ if (r.added_user + r.added_project + r.skills + r.hooks + r.rules + r.sessions + r.sessions_skipped + r.sessions_failed == 0 and r.skipped == 0) {
+ try out.writeAll("nothing to adopt: no Claude/Cursor setup or Claude conversations found.\n");
try out.flush();
return;
}
@@ -41,7 +49,10 @@ pub fn command(io: Io, arena: Allocator, home: []const u8, cwd: []const u8, out:
try out.print("copied {d} skill(s) → ~/.codegraff/skills and .harness/skills\n", .{r.skills});
if (r.hooks > 0) try out.print("copied {d} hook(s) → ~/.codegraff/hooks (PreToolUse Read/Edit skipped)\n", .{r.hooks});
if (r.rules > 0) try out.print("copied {d} rule file(s) → .harness/\n", .{r.rules});
- try out.writeAll("new MCP servers still need /mcp trust or --yolo to connect.\n");
+ if (r.sessions > 0) try out.print("imported {d} Claude conversation(s) → .graff/sessions — /resume to continue\n", .{r.sessions});
+ if (r.sessions_skipped > 0) try out.print("skipped {d} existing conversation save(s)\n", .{r.sessions_skipped});
+ if (r.sessions_failed > 0) try out.print("could not import {d} Claude transcript(s) (unreadable, invalid or too large)\n", .{r.sessions_failed});
+ if (r.added_user + r.added_project > 0) try out.writeAll("new MCP servers still need /mcp trust or --yolo to connect.\n");
try out.flush();
}
diff --git a/src/adopt_conversation.zig b/src/adopt_conversation.zig
new file mode 100644
index 00000000..c4e9da96
--- /dev/null
+++ b/src/adopt_conversation.zig
@@ -0,0 +1,269 @@
+//! Claude JSONL → ordinary Anthropic-wire saved history (#1495).
+const std = @import("std");
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+pub const Conversation = struct {
+ messages: std.json.Array,
+ title: []const u8 = "Imported Claude conversation",
+ model: []const u8 = @import("provider.zig").provider_specs[0].default_model,
+ updated_ms: i64 = 0,
+ title_priority: u8 = 0,
+};
+
+/// Foreign tool receipts remain historical context across wire formats. They
+/// never become executable calls on the newly selected provider.
+pub fn forProvider(a: Allocator, history: std.json.Array, kind: @import("provider.zig").Provider.Kind) !std.json.Array {
+ if (kind == .anthropic) return history;
+ var out = std.json.Array.init(a);
+ for (history.items) |msg| {
+ const role = string(msg.object, "role") orelse continue;
+ const content = msg.object.get("content") orelse continue;
+ var body: std.Io.Writer.Allocating = .init(a);
+ if (content == .string) {
+ try body.writer.writeAll(content.string);
+ } else if (content == .array) {
+ for (content.array.items) |block| {
+ if (block != .object) continue;
+ const typ = string(block.object, "type") orelse continue;
+ if (std.mem.eql(u8, typ, "text")) {
+ try body.writer.print("{s}\n", .{string(block.object, "text") orelse ""});
+ } else if (std.mem.eql(u8, typ, "tool_use")) {
+ try body.writer.print("Historical tool call {s} ({s}): {s}\n", .{
+ string(block.object, "name") orelse "tool",
+ string(block.object, "id") orelse "",
+ try std.json.Stringify.valueAlloc(a, block.object.get("input") orelse .null, .{}),
+ });
+ } else if (std.mem.eql(u8, typ, "tool_result")) {
+ try body.writer.print("Historical tool result ({s}){s}: {s}\n", .{
+ string(block.object, "tool_use_id") orelse "",
+ if (flag(block.object, "is_error")) " [error]" else "",
+ @import("messages.zig").toolContentString(a, block.object.get("content") orelse .null),
+ });
+ }
+ }
+ }
+ const trimmed = std.mem.trim(u8, body.written(), " \t\r\n");
+ if (trimmed.len > 0) try out.append(try @import("messages.zig").textMessage(a, role, trimmed));
+ }
+ return out;
+}
+
+pub fn string(obj: std.json.ObjectMap, key: []const u8) ?[]const u8 {
+ const v = obj.get(key) orelse return null;
+ return if (v == .string and v.string.len > 0) v.string else null;
+}
+
+fn flag(obj: std.json.ObjectMap, key: []const u8) bool {
+ const v = obj.get(key) orelse return false;
+ return v == .bool and v.bool;
+}
+
+pub fn text(a: Allocator, body: []const u8) !Value {
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(a, "type", .{ .string = "text" });
+ try obj.put(a, "text", .{ .string = body });
+ return .{ .object = obj };
+}
+
+fn append(a: Allocator, history: *std.json.Array, role: []const u8, block: Value) !void {
+ if (history.items.len > 0) {
+ const last = &history.items[history.items.len - 1];
+ if (std.mem.eql(u8, string(last.object, "role").?, role)) {
+ try last.object.getPtr("content").?.array.append(block);
+ return;
+ }
+ }
+ var blocks = std.json.Array.init(a);
+ try blocks.append(block);
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(a, "role", .{ .string = role });
+ try obj.put(a, "content", .{ .array = blocks });
+ try history.append(.{ .object = obj });
+}
+
+pub fn convert(a: Allocator, data: []const u8, cwd: []const u8) !Conversation {
+ var result: Conversation = .{ .messages = std.json.Array.init(a) };
+ var seen: std.StringHashMapUnmanaged(void) = .empty;
+ var calls: std.StringHashMapUnmanaged(void) = .empty;
+ var outputs: std.StringHashMapUnmanaged(void) = .empty;
+ var title_rank: u8 = 0;
+ var lines = std.mem.splitScalar(u8, data, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len == 0) continue;
+ const entry = std.json.parseFromSliceLeaky(Value, a, line, .{ .allocate = .alloc_always }) catch {
+ // A running/crashed writer can leave only its final line unfinished.
+ if (lines.peek() == null) break;
+ return error.InvalidTranscript;
+ };
+ if (entry != .object or flag(entry.object, "isSidechain")) continue;
+ const obj = entry.object;
+ if (string(obj, "cwd")) |workspace| {
+ // Encoded project paths can collide (e.g. a-b and a/b).
+ if (!@import("session_index.zig").sameWorkspace(workspace, cwd)) return error.OtherWorkspace;
+ }
+ const typ = string(obj, "type") orelse continue;
+ if (string(obj, "timestamp")) |ts| result.updated_ms = @max(result.updated_ms, timestampMs(ts) orelse 0);
+ const rank: u8 = if (std.mem.eql(u8, typ, "custom-title")) 3 else if (std.mem.eql(u8, typ, "ai-title")) 2 else if (std.mem.eql(u8, typ, "summary")) 1 else 0;
+ if (rank > 0 and rank >= title_rank) {
+ if (string(obj, if (rank == 3) "customTitle" else if (rank == 2) "aiTitle" else "summary")) |title| {
+ result.title = title;
+ title_rank = rank;
+ }
+ }
+ if (!std.mem.eql(u8, typ, "user") and !std.mem.eql(u8, typ, "assistant")) continue;
+ if (string(obj, "uuid")) |uuid| {
+ const gop = try seen.getOrPut(a, uuid);
+ if (gop.found_existing) continue;
+ }
+ const msg = obj.get("message") orelse continue;
+ if (msg != .object) continue;
+ if (std.mem.eql(u8, typ, "assistant")) {
+ if (string(msg.object, "model")) |model| {
+ if (std.mem.startsWith(u8, model, "claude-")) result.model = model;
+ }
+ }
+ const content = msg.object.get("content") orelse continue;
+ if (content == .string) {
+ if (content.string.len > 0) try append(a, &result.messages, typ, try text(a, content.string));
+ continue;
+ }
+ if (content != .array) continue;
+ for (content.array.items) |block| {
+ if (block != .object) continue;
+ const bt = string(block.object, "type") orelse continue;
+ if (std.mem.eql(u8, bt, "text")) {
+ if (string(block.object, "text")) |body| try append(a, &result.messages, typ, try text(a, body));
+ } else if (std.mem.eql(u8, typ, "assistant") and std.mem.eql(u8, bt, "tool_use")) {
+ const id = string(block.object, "id") orelse continue;
+ const name = string(block.object, "name") orelse continue;
+ const input = block.object.get("input") orelse continue;
+ if (input != .object) continue;
+ const gop = try calls.getOrPut(a, id);
+ if (gop.found_existing) continue;
+ var tool: std.json.ObjectMap = .empty;
+ try tool.put(a, "type", .{ .string = "tool_use" });
+ try tool.put(a, "id", .{ .string = id });
+ try tool.put(a, "name", .{ .string = name });
+ try tool.put(a, "input", input);
+ try append(a, &result.messages, typ, .{ .object = tool });
+ } else if (std.mem.eql(u8, typ, "user") and std.mem.eql(u8, bt, "tool_result")) {
+ const id = string(block.object, "tool_use_id") orelse continue;
+ if (!calls.contains(id) or !pendingTool(result.messages.items, id)) continue;
+ const gop = try outputs.getOrPut(a, id);
+ if (gop.found_existing) continue;
+ var tool: std.json.ObjectMap = .empty;
+ try tool.put(a, "type", .{ .string = "tool_result" });
+ try tool.put(a, "tool_use_id", .{ .string = id });
+ var body: Value = block.object.get("content") orelse .{ .string = "" };
+ if (body == .array) {
+ var blocks = std.json.Array.init(a);
+ for (body.array.items) |b| {
+ if (b == .object) {
+ if (string(b.object, "type")) |t| {
+ if (std.mem.eql(u8, t, "text")) {
+ if (string(b.object, "text")) |s| try blocks.append(try text(a, s));
+ }
+ }
+ }
+ }
+ body = .{ .array = blocks };
+ } else if (body != .string) body = .{ .string = try std.json.Stringify.valueAlloc(a, body, .{}) };
+ try tool.put(a, "content", body);
+ if (flag(block.object, "is_error")) try tool.put(a, "is_error", .{ .bool = true });
+ try append(a, &result.messages, typ, .{ .object = tool });
+ }
+ }
+ }
+ if (result.messages.items.len == 0) return error.EmptyTranscript;
+ // Resolve interrupted calls without replaying them. Keep each result directly
+ // after its assistant turn; orphan results never enter the imported history.
+ var history = std.json.Array.init(a);
+ var i: usize = 0;
+ while (i < result.messages.items.len) : (i += 1) {
+ const msg = result.messages.items[i];
+ try history.append(msg);
+ if (!std.mem.eql(u8, string(msg.object, "role").?, "assistant")) continue;
+ var user = std.json.Array.init(a);
+ var rest = std.json.Array.init(a);
+ if (i + 1 < result.messages.items.len) {
+ const next = result.messages.items[i + 1];
+ for (next.object.get("content").?.array.items) |b| {
+ if (std.mem.eql(u8, string(b.object, "type").?, "tool_result")) try user.append(b) else try rest.append(b);
+ }
+ }
+ for (msg.object.get("content").?.array.items) |b| {
+ if (!std.mem.eql(u8, string(b.object, "type").?, "tool_use")) continue;
+ const id = string(b.object, "id").?;
+ var found = false;
+ for (user.items) |u| {
+ if (std.mem.eql(u8, string(u.object, "tool_use_id").?, id)) found = true;
+ }
+ if (found) continue;
+ var missing: std.json.ObjectMap = .empty;
+ try missing.put(a, "type", .{ .string = "tool_result" });
+ try missing.put(a, "tool_use_id", .{ .string = id });
+ try missing.put(a, "content", .{ .string = "Claude transcript ended before this tool result was recorded. Check whether it took effect before retrying." });
+ try missing.put(a, "is_error", .{ .bool = true });
+ try user.append(.{ .object = missing });
+ }
+ try user.appendSlice(rest.items);
+ if (user.items.len > 0) {
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(a, "role", .{ .string = "user" });
+ try obj.put(a, "content", .{ .array = user });
+ try history.append(.{ .object = obj });
+ if (i + 1 < result.messages.items.len) i += 1;
+ }
+ }
+ result.messages = history;
+ result.title_priority = title_rank;
+ if (title_rank == 0) {
+ for (history.items) |msg| {
+ const prompt = @import("messages.zig").userPromptText(msg) orelse continue;
+ const trimmed = std.mem.trim(u8, prompt, " \t\r\n");
+ if (trimmed.len == 0) continue;
+ result.title = @import("util.zig").utf8Prefix(trimmed, @min(trimmed.len, 80));
+ break;
+ }
+ }
+ return result;
+}
+
+fn pendingTool(history: []const Value, id: []const u8) bool {
+ var i = history.len;
+ while (i > 0) {
+ i -= 1;
+ const msg = history[i];
+ if (!std.mem.eql(u8, string(msg.object, "role").?, "assistant")) continue;
+ for (msg.object.get("content").?.array.items) |block| {
+ if (string(block.object, "id")) |call_id| {
+ if (std.mem.eql(u8, call_id, id)) return true;
+ }
+ }
+ return false;
+ }
+ return false;
+}
+
+/// Date.toISOString timestamps emitted by Claude's transcript writer (UTC).
+pub fn timestampMs(ts: []const u8) ?i64 {
+ if ((ts.len != 24 and ts.len != 20) or ts[4] != '-' or ts[7] != '-' or ts[10] != 'T' or ts[13] != ':' or ts[16] != ':' or ts[ts.len - 1] != 'Z') return null;
+ const year = std.fmt.parseInt(u16, ts[0..4], 10) catch return null;
+ const month = std.fmt.parseInt(u8, ts[5..7], 10) catch return null;
+ const day = std.fmt.parseInt(u8, ts[8..10], 10) catch return null;
+ const hour = std.fmt.parseInt(u8, ts[11..13], 10) catch return null;
+ const minute = std.fmt.parseInt(u8, ts[14..16], 10) catch return null;
+ const second = std.fmt.parseInt(u8, ts[17..19], 10) catch return null;
+ const ms: i64 = if (ts.len == 24 and ts[19] == '.') std.fmt.parseInt(u16, ts[20..23], 10) catch return null else if (ts.len == 20) 0 else return null;
+ if (year < 1970 or month == 0 or month > 12 or day == 0 or hour > 23 or minute > 59 or second > 59) return null;
+ const leap = std.time.epoch.isLeapYear(year);
+ const months = [_]u8{ 31, if (leap) 29 else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
+ if (day > months[month - 1]) return null;
+ const y: i64 = year - 1;
+ var days: i64 = (@as(i64, year) - 1970) * 365 + (@divTrunc(y, 4) - 492) - (@divTrunc(y, 100) - 19) + (@divTrunc(y, 400) - 4);
+ for (months[0 .. month - 1]) |n| days += n;
+ days += day - 1;
+ return ((days * 24 + hour) * 3600 + @as(i64, minute) * 60 + second) * 1000 + ms;
+}
diff --git a/src/adopt_sessions.zig b/src/adopt_sessions.zig
new file mode 100644
index 00000000..98792242
--- /dev/null
+++ b/src/adopt_sessions.zig
@@ -0,0 +1,160 @@
+//! Explicit, non-overwriting Claude conversation import (#1495).
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const conversation = @import("adopt_conversation.zig");
+const session = @import("session_index.zig");
+
+pub const Report = struct { imported: usize = 0, skipped: usize = 0, failed: usize = 0 };
+
+pub fn projectSlug(a: Allocator, cwd: []const u8) ![]const u8 {
+ const slug = try a.dupe(u8, cwd);
+ for (slug) |*ch| if (!std.ascii.isAlphanumeric(ch.*)) {
+ ch.* = '-';
+ };
+ return slug;
+}
+
+pub fn run(io: Io, a: Allocator, home: []const u8, cwd: []const u8) !Report {
+ if (home.len == 0) return .{};
+ return runConfig(io, a, try std.fmt.allocPrint(a, "{s}/.claude", .{home}), cwd, null, null);
+}
+
+/// Import just one transcript, without adopting hooks, skills or MCP settings.
+pub fn importOne(io: Io, a: Allocator, config: []const u8, cwd: []const u8, id: []const u8, project_name: ?[]const u8) ![]const u8 {
+ if (!session.validSessionName(id) or std.mem.startsWith(u8, id, "agent-")) return error.InvalidSessionName;
+ const base = try std.fmt.allocPrint(a, "claude-{s}", .{id});
+ if (!session.validSessionName(base)) return error.InvalidSessionName;
+ const report = try runConfig(io, a, config, cwd, id, project_name);
+ if (report.imported + report.skipped == 0 or report.failed > 0) return error.ClaudeImportFailed;
+ return base;
+}
+
+fn runConfig(io: Io, a: Allocator, config: []const u8, cwd: []const u8, only: ?[]const u8, project_name: ?[]const u8) !Report {
+ var report: Report = .{};
+ const projects = try std.fmt.allocPrint(a, "{s}/projects", .{config});
+ var dir = Io.Dir.cwd().openDir(io, projects, .{ .iterate = true }) catch |err| {
+ if (err == error.FileNotFound) return report;
+ return err;
+ };
+ defer dir.close(io);
+ if (project_name) |name| {
+ if (!session.validSessionName(name) or name.len > 64) return error.InvalidSessionName;
+ try importProject(io, a, dir, name, cwd, only, &report);
+ return report;
+ }
+ const slug = try projectSlug(a, cwd);
+ if (slug.len <= 200) {
+ try importProject(io, a, dir, slug, cwd, only, &report);
+ } else {
+ // Claude appends an implementation-specific hash after truncating long
+ // names. Validate the transcript cwd instead of guessing that hash.
+ var it = dir.iterate();
+ while (try it.next(io)) |entry| {
+ if (entry.kind == .directory and std.mem.startsWith(u8, entry.name, slug[0..200]))
+ try importProject(io, a, dir, entry.name, cwd, only, &report);
+ }
+ }
+ return report;
+}
+
+fn importProject(io: Io, a: Allocator, projects: Io.Dir, name: []const u8, cwd: []const u8, only: ?[]const u8, report: *Report) !void {
+ var project = projects.openDir(io, name, .{ .iterate = true }) catch |err| {
+ if (err == error.FileNotFound) return;
+ return err;
+ };
+ defer project.close(io);
+ const index_data = project.readFileAlloc(io, "sessions-index.json", a, .limited(8 << 20)) catch "";
+ const index = std.json.parseFromSliceLeaky(std.json.Value, a, index_data, .{}) catch .null;
+ var workspace = try Io.Dir.cwd().openDir(io, cwd, .{});
+ defer workspace.close(io);
+ var it = project.iterate();
+ while (try it.next(io)) |entry| {
+ if (entry.kind != .file or !std.mem.endsWith(u8, entry.name, ".jsonl") or std.mem.startsWith(u8, entry.name, "agent-")) continue;
+ const id = entry.name[0 .. entry.name.len - ".jsonl".len];
+ if (only) |wanted| if (!std.mem.eql(u8, id, wanted)) continue;
+ if (!session.validSessionName(id)) continue;
+ const base = try std.fmt.allocPrint(a, "claude-{s}", .{id});
+ if (!session.validSessionName(base)) {
+ report.failed += 1;
+ continue;
+ }
+ const dest = try session.sessionPath(a, base);
+ if (workspace.statFile(io, dest, .{}) catch null != null) {
+ report.skipped += 1;
+ continue;
+ }
+ // Release JSONL/parser allocations after each file, including skips.
+ var scratch = std.heap.ArenaAllocator.init(std.heap.page_allocator);
+ defer scratch.deinit();
+ const temp = scratch.allocator();
+ const data = project.readFileAlloc(io, entry.name, temp, .limited(64 << 20)) catch {
+ report.failed += 1;
+ continue;
+ };
+ var converted = conversation.convert(temp, data, cwd) catch |err| {
+ if (err != error.EmptyTranscript and err != error.OtherWorkspace) report.failed += 1;
+ continue;
+ };
+ applyIndex(&converted, index, id);
+ if (converted.updated_ms == 0) {
+ if (project.statFile(io, entry.name, .{})) |st| {
+ converted.updated_ms = @intCast(@divTrunc(st.mtime.nanoseconds, std.time.ns_per_ms));
+ } else |_| {}
+ }
+ var out: Io.Writer.Allocating = .init(temp);
+ var json: std.json.Stringify = .{ .writer = &out.writer };
+ // List metadata must precede the potentially large messages array.
+ try json.write(.{
+ .title = converted.title,
+ .updated_ms = converted.updated_ms,
+ .workspace = cwd,
+ .provider = "anthropic",
+ .model = converted.model,
+ .imported_from = "claude",
+ .messages = std.json.Value{ .array = converted.messages },
+ });
+ const bytes = out.written();
+ if (bytes.len > 8 << 20) {
+ report.failed += 1;
+ continue;
+ }
+ @import("graff_dir.zig").ensure(io, workspace);
+ try workspace.createDirPath(io, session.sessions_dir);
+ // Exclusive create also protects against another importer racing us.
+ var file = workspace.createFile(io, dest, .{ .exclusive = true }) catch |err| {
+ if (err == error.PathAlreadyExists) report.skipped += 1 else report.failed += 1;
+ continue;
+ };
+ defer file.close(io);
+ var writer = file.writer(io, &.{});
+ writer.interface.writeAll(bytes) catch {
+ workspace.deleteFile(io, dest) catch {};
+ report.failed += 1;
+ continue;
+ };
+ report.imported += 1;
+ }
+}
+
+fn applyIndex(result: *conversation.Conversation, index: std.json.Value, id: []const u8) void {
+ if (index != .object) return;
+ const entries = index.object.get("entries") orelse return;
+ if (entries != .array) return;
+ for (entries.array.items) |entry| {
+ if (entry != .object) continue;
+ const sid = conversation.string(entry.object, "sessionId") orelse continue;
+ if (!std.mem.eql(u8, sid, id)) continue;
+ if (result.title_priority < 3) {
+ if (conversation.string(entry.object, "customTitle")) |title| {
+ result.title = title;
+ result.title_priority = 3;
+ }
+ }
+ if (result.title_priority < 1) {
+ if (conversation.string(entry.object, "summary")) |title| result.title = title;
+ }
+ if (conversation.string(entry.object, "modified")) |ts| result.updated_ms = @max(result.updated_ms, conversation.timestampMs(ts) orelse 0);
+ return;
+ }
+}
diff --git a/src/adopt_sessions_tests.zig b/src/adopt_sessions_tests.zig
new file mode 100644
index 00000000..052ce729
--- /dev/null
+++ b/src/adopt_sessions_tests.zig
@@ -0,0 +1,224 @@
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const testing = std.testing;
+const importer = @import("adopt_sessions.zig");
+const converter = @import("adopt_conversation.zig");
+
+const transcript =
+ \\{"type":"user","uuid":"u1","timestamp":"2026-01-01T00:00:00.000Z","message":{"role":"user","content":"Fix the widget"}}
+ \\{"type":"assistant","uuid":"a1","message":{"model":"claude-sonnet-4-5","content":[{"type":"thinking","thinking":"secret","signature":"signed"},{"type":"redacted_thinking","data":"opaque"}]}}
+ \\{"type":"assistant","uuid":"a2","message":{"model":"claude-sonnet-4-5","content":[{"type":"text","text":"Checking"}]}}
+ \\{"type":"assistant","uuid":"a3","message":{"content":[{"type":"tool_use","id":"tool-1","name":"Bash","input":{"command":"pwd"}}]}}
+ \\{"type":"assistant","uuid":"a3","message":{"content":[{"type":"tool_use","id":"tool-1","name":"Bash","input":{"command":"pwd"}}]}}
+ \\{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"tool-1","is_error":true,"content":[{"type":"text","text":"not found"}]}]}}
+ \\{"type":"assistant","isSidechain":true,"message":{"content":[{"type":"text","text":"sidechain secret"}]}}
+ \\{"type":"assistant","timestamp":"2026-01-01T00:01:00.123Z","message":{"content":[{"type":"text","text":"Done"}]}}
+ \\{"type":"progress","data":{"irrelevant":"progress"}}
+;
+
+fn blocks(msg: Value) []const Value {
+ return msg.object.get("content").?.array.items;
+}
+
+test "Claude conversion preserves text tool pairs model and time without signed thinking" {
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const c = try converter.convert(a, transcript, "/project");
+ try testing.expectEqual(@as(usize, 4), c.messages.items.len);
+ try testing.expectEqualStrings("Fix the widget", c.title);
+ try testing.expectEqualStrings("claude-sonnet-4-5", c.model);
+ try testing.expectEqual(@as(i64, 1767225660123), c.updated_ms);
+ try testing.expectEqual(@as(usize, 2), blocks(c.messages.items[1]).len);
+ const call = blocks(c.messages.items[1])[1].object;
+ try testing.expectEqualStrings("tool-1", converter.string(call, "id").?);
+ try testing.expectEqualStrings("pwd", converter.string(call.get("input").?.object, "command").?);
+ const output = blocks(c.messages.items[2])[0].object;
+ try testing.expectEqualStrings("tool-1", converter.string(output, "tool_use_id").?);
+ try testing.expect(output.get("is_error").?.bool);
+ const serialized = try std.json.Stringify.valueAlloc(a, Value{ .array = c.messages }, .{});
+ try testing.expect(std.mem.indexOf(u8, serialized, "secret") == null);
+ try testing.expect(std.mem.indexOf(u8, serialized, "signature") == null);
+ try testing.expect(std.mem.indexOf(u8, serialized, "not found") != null);
+}
+
+test "Claude interrupted calls get an error receipt and orphan results are discarded" {
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const c = try converter.convert(arena.allocator(),
+ \\{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"orphan","content":"orphan"},{"type":"text","text":"Continue"}]}}
+ \\{"type":"assistant","message":{"content":[{"type":"tool_use","id":"unfinished","name":"Edit","input":{}}]}}
+ \\{"type":"user","message":{"content":"next prompt"}}
+ , "/project");
+ try testing.expectEqual(@as(usize, 3), c.messages.items.len);
+ const user = blocks(c.messages.items[2]);
+ try testing.expectEqual(@as(usize, 2), user.len);
+ try testing.expectEqualStrings("unfinished", converter.string(user[0].object, "tool_use_id").?);
+ try testing.expect(user[0].object.get("is_error").?.bool);
+ try testing.expectEqualStrings("next prompt", converter.string(user[1].object, "text").?);
+}
+
+test "Claude metadata titles have priority and incomplete final lines are tolerated" {
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const c = try converter.convert(a,
+ \\{"type":"summary","summary":"Summary"}
+ \\{"type":"custom-title","customTitle":"Named conversation"}
+ \\{"type":"ai-title","aiTitle":"Generated title"}
+ \\{"type":"user","message":{"content":"Question"}}
+ \\{"type":"assistant"
+ , "/project");
+ try testing.expectEqualStrings("Named conversation", c.title);
+ try testing.expectError(error.InvalidTranscript, converter.convert(a, "bad\n{}", "/project"));
+ try testing.expectError(error.EmptyTranscript, converter.convert(a, "{\"type\":\"progress\"}", "/project"));
+ try testing.expectError(error.OtherWorkspace, converter.convert(a, "{\"cwd\":\"/other\",\"type\":\"user\",\"message\":{\"content\":\"wrong\"}}", "/project"));
+}
+
+test "Claude UTC timestamp parser validates dates and leap years" {
+ try testing.expectEqual(@as(i64, 0), converter.timestampMs("1970-01-01T00:00:00Z").?);
+ try testing.expectEqual(@as(i64, 1709251199999), converter.timestampMs("2024-02-29T23:59:59.999Z").?);
+ try testing.expect(converter.timestampMs("2023-02-29T00:00:00.000Z") == null);
+ try testing.expect(converter.timestampMs("2026-01-01T24:00:00.000Z") == null);
+ try testing.expect(converter.timestampMs("bad") == null);
+}
+
+test "Claude import command creates discoverable loadable saves and never overwrites" {
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const io = testing.io;
+ const base = try tmp.dir.realPathFileAlloc(io, ".", a);
+ const home = try std.fmt.allocPrint(a, "{s}/home", .{base});
+ const cwd = try std.fmt.allocPrint(a, "{s}/project.with_punctuation", .{base});
+ try Io.Dir.cwd().createDirPath(io, cwd);
+ const source = try std.fmt.allocPrint(a, "{s}/.claude/projects/{s}", .{ home, try importer.projectSlug(a, cwd) });
+ try Io.Dir.cwd().createDirPath(io, source);
+ const input = try std.fmt.allocPrint(a, "{s}/fixture.jsonl", .{source});
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = input, .data = transcript });
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}/sessions-index.json", .{source}), .data =
+ \\{"entries":[{"sessionId":"fixture","customTitle":"Widget task","modified":"2026-01-01T00:02:00.000Z"}]}
+ });
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}/broken.jsonl", .{source}), .data = "invalid\n{}" });
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}/agent-child.jsonl", .{source}), .data = transcript });
+ try Io.Dir.cwd().createDirPath(io, try std.fmt.allocPrint(a, "{s}/fixture/subagents", .{source}));
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}/fixture/subagents/child.jsonl", .{source}), .data = transcript });
+
+ // First-run adoption must not copy conversation history.
+ _ = try @import("adopt.zig").maybeFirstRun(io, a, home, cwd);
+ const saved = try std.fmt.allocPrint(a, "{s}/.graff/sessions/claude-fixture.session.json", .{cwd});
+ try testing.expectError(error.FileNotFound, Io.Dir.cwd().statFile(io, saved, .{}));
+ var out: Io.Writer.Allocating = .init(a);
+ try @import("adopt.zig").command(io, a, home, cwd, &out.writer);
+ try testing.expect(std.mem.indexOf(u8, out.written(), "imported 1 Claude conversation(s)") != null);
+ try testing.expect(std.mem.indexOf(u8, out.written(), "could not import 1") != null);
+ const bytes = try Io.Dir.cwd().readFileAlloc(io, saved, a, .limited(8 << 20));
+ const meta = @import("session_index.zig").sessionMetaFromBytes(a, bytes);
+ try testing.expectEqualStrings("Widget task", meta.title.?);
+ try testing.expectEqual(@as(i64, 1767225720000), meta.updated_ms);
+ try testing.expectEqualStrings(cwd, meta.workspace.?);
+ try testing.expect((try Io.Dir.cwd().statFile(io, try std.fmt.allocPrint(a, "{s}/.graff/.gitignore", .{cwd}), .{})).size > 0);
+
+ // Both frontends use this same session loader. Home discovery lets the
+ // test exercise it without mutating the process cwd.
+ var client: std.http.Client = .{ .allocator = testing.allocator, .io = io };
+ defer client.deinit();
+ var keys: @import("provider.zig").Keys = .{ .values = @splat("test-key") };
+ var root: @import("agent.zig").Agent = .{
+ .gpa = testing.allocator,
+ .arena = a,
+ .io = io,
+ .client = &client,
+ .provider = try keys.providerById("anthropic", "fixture"),
+ .messages = std.json.Array.init(a),
+ .sub = false,
+ .label = "root",
+ .out = null,
+ .home = cwd,
+ };
+ const listing = @import("session_index.zig").listSavedSessionsAll(&root, a);
+ var found = false;
+ for (listing.items) |entry| {
+ if (std.mem.eql(u8, entry.base, "claude-fixture")) found = true;
+ }
+ try testing.expect(found);
+ try @import("session.zig").loadSession(&root, &keys, a, "claude-fixture");
+ try testing.expectEqualStrings("Widget task", root.session_title.?);
+ try testing.expectEqual(@as(usize, 4), root.messages.items.len);
+ const body = try root.buildBody(null, false, false, false);
+ defer testing.allocator.free(body);
+ try testing.expect(std.mem.indexOf(u8, body, "not found") != null);
+ try testing.expect(std.mem.indexOf(u8, body, "sidechain secret") == null);
+ try testing.expect(std.mem.indexOf(u8, body, "\"thinking\":\"secret\"") == null);
+
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = saved, .data = "continued in graff" });
+ const again = try importer.run(io, a, home, cwd);
+ try testing.expectEqual(@as(usize, 0), again.imported);
+ try testing.expectEqual(@as(usize, 1), again.skipped);
+ try testing.expectEqualStrings("continued in graff", try Io.Dir.cwd().readFileAlloc(io, saved, a, .limited(100)));
+}
+
+test "Claude import missing project is a no-op" {
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const home = try tmp.dir.realPathFileAlloc(testing.io, ".", a);
+ try testing.expectEqual(@as(usize, 0), (try importer.run(testing.io, a, home, "/project")).imported);
+ try testing.expectEqual(@as(usize, 0), (try importer.run(testing.io, a, "", "/project")).imported);
+ try testing.expectEqualStrings("-a-b-c-d", try importer.projectSlug(a, "/a.b/c_d"));
+}
+
+test "selected import uses the configured graff provider without Claude credentials" {
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const io = testing.io;
+ const cwd = try tmp.dir.realPathFileAlloc(io, ".", a);
+ const config = try std.fmt.allocPrint(a, "{s}/source-config", .{cwd});
+ const source = try std.fmt.allocPrint(a, "{s}/projects/{s}", .{ config, try importer.projectSlug(a, cwd) });
+ try Io.Dir.cwd().createDirPath(io, source);
+ for ([_][]const u8{ "selected", "other" }) |id| {
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}/{s}.jsonl", .{ source, id }), .data = transcript });
+ }
+ try testing.expectEqualStrings("claude-selected", try importer.importOne(io, a, config, cwd, "selected", null));
+ try testing.expectError(error.FileNotFound, tmp.dir.statFile(io, ".graff/sessions/claude-other.session.json", .{}));
+ try testing.expectError(error.FileNotFound, tmp.dir.statFile(io, ".mcp.json", .{}));
+ try testing.expectError(error.ClaudeImportFailed, importer.importOne(io, a, config, cwd, "missing", null));
+ try testing.expectError(error.InvalidSessionName, importer.importOne(io, a, config, cwd, "../selected", null));
+ try testing.expectEqualStrings("claude-selected", try importer.importOne(io, a, config, cwd, "selected", null));
+
+ var client: std.http.Client = .{ .allocator = testing.allocator, .io = io };
+ defer client.deinit();
+ var keys: @import("provider.zig").Keys = .{ .values = @splat("") };
+ for ([_]@import("provider.zig").Provider.Kind{ .anthropic, .openai, .responses }) |kind| {
+ var root: @import("agent.zig").Agent = .{
+ .gpa = testing.allocator,
+ .arena = a,
+ .io = io,
+ .client = &client,
+ .provider = .{ .id = "configured-route", .kind = kind, .auth = .bearer, .url = "", .api_key = "configured-key", .model = "configured-model", .context = 100_000 },
+ .messages = std.json.Array.init(a),
+ .sub = false,
+ .label = "root",
+ .out = null,
+ .home = cwd,
+ };
+ try @import("session.zig").loadSession(&root, &keys, a, "claude-selected");
+ try testing.expectEqualStrings("configured-route", root.provider.id);
+ try testing.expectEqualStrings("configured-model", root.provider.model);
+ const body = try root.buildBody(null, false, false, false);
+ defer testing.allocator.free(body);
+ try testing.expect(std.mem.indexOf(u8, body, "Fix the widget") != null);
+ try testing.expect(std.mem.indexOf(u8, body, "pwd") != null);
+ try testing.expect(std.mem.indexOf(u8, body, "not found") != null);
+ try testing.expect(std.mem.indexOf(u8, body, "sidechain secret") == null);
+ try testing.expect(std.mem.indexOf(u8, body, "\"thinking\":\"secret\"") == null);
+ }
+}
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index 26878ec2..1e56eec1 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -125,7 +125,7 @@ pub const commands = [_]Item{
.{ .name = "/theme", .usage = "/theme [name]", .desc = "pick a color theme; /theme off resets to your terminal default; persists" },
.{ .name = "/fleet", .usage = "/fleet [on|off]", .desc = "federated DGM contribution (propose/submit/elite_pull)" },
.{ .name = "/mcp", .usage = "/mcp [add …]", .desc = "list MCP servers/tools; /mcp add <name> <cmd> [args...] connects one live" },
- .{ .name = "/import-claude", .desc = "copy Claude/Cursor MCP servers and skills into ~/.codegraff and this repo" },
+ .{ .name = "/import-claude", .desc = "copy Claude/Cursor setup and import this project's Claude conversations for /resume" },
.{ .name = "/help", .desc = "list every command" },
};
diff --git a/src/main.zig b/src/main.zig
index d3009a54..00fb2ef9 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -82,6 +82,7 @@ test {
_ = serde;
_ = mcp_cli;
_ = @import("adopt.zig");
+ _ = @import("adopt_sessions_tests.zig");
_ = cli;
_ = @import("version_status.zig");
_ = prompts;
diff --git a/src/mcp_cli.zig b/src/mcp_cli.zig
index dd8c6d94..5336509c 100644
--- a/src/mcp_cli.zig
+++ b/src/mcp_cli.zig
@@ -208,7 +208,8 @@ fn mcpCliUsage(w: *Io.Writer) !void {
\\ graff mcp install [--directory PATH] [--port N] install HTTP service and client entries
\\ graff mcp serve [--http] [--port N] [--model NAME] [--yolo] expose run_task over stdio or HTTP
\\ graff mcp list servers in .mcp.json + ~/.codegraff/mcp.json
- \\ graff mcp import copy Claude/Cursor MCP + skills into graff folders
+ \\ graff mcp import copy setup and import this project's Claude history
+ \\ graff mcp import-session <id> import only one Claude conversation into graff
\\ graff mcp add <url | @scope/package | uvx:package | '{json}' | -> infer, save, then connect to check it
\\ graff mcp add <name> [--env K=V] [--header K=V] look up a server (codegraff.com/mcp, then the MCP registry)
\\ graff mcp add … --everywhere save to ~/.codegraff/mcp.json (every project) instead of ./.mcp.json
@@ -308,10 +309,18 @@ pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, en
// Reads (list/login) see project + global; writes stay project-local.
const global_path = mcp_config.globalPath(arena, home, environ_map);
- if (args.len > 0 and (std.mem.eql(u8, args[0], "import") or std.mem.eql(u8, args[0], "import-claude") or std.mem.eql(u8, args[0], "adopt"))) {
+ if (args.len > 0 and (std.mem.eql(u8, args[0], "import") or std.mem.eql(u8, args[0], "import-claude") or std.mem.eql(u8, args[0], "adopt") or std.mem.eql(u8, args[0], "import-session"))) {
var cwd_buf: [std.fs.max_path_bytes]u8 = undefined;
const n = Io.Dir.cwd().realPath(io, &cwd_buf) catch 0;
const cwd = if (n > 0) cwd_buf[0..n] else ".";
+ if (std.mem.eql(u8, args[0], "import-session")) {
+ if (args.len != 2) return error.InvalidArguments;
+ const config = environ_map.get("CLAUDE_CONFIG_DIR") orelse try std.fmt.allocPrint(arena, "{s}/.claude", .{home});
+ const name = try @import("adopt_sessions.zig").importOne(io, arena, config, cwd, args[1], environ_map.get("CLAUDE_CODE_PROJECT_DIR_NAME"));
+ try out.interface.print("{s}\n", .{name});
+ try out.interface.flush();
+ return;
+ }
try @import("adopt.zig").command(io, arena, home, cwd, &out.interface);
return;
}
diff --git a/src/session.zig b/src/session.zig
index e781b202..a755b604 100644
--- a/src/session.zig
+++ b/src/session.zig
@@ -473,7 +473,8 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8
const obj = parsed.object;
const pid = if (obj.get("provider")) |v| v.string else return error.BadSession;
const model = if (obj.get("model")) |v| v.string else return error.BadSession;
- const msgs = if (obj.get("messages")) |v| (if (v == .array) v.array else return error.BadSession) else return error.BadSession;
+ var msgs = if (obj.get("messages")) |v| (if (v == .array) v.array else return error.BadSession) else return error.BadSession;
+ const claude_import = if (obj.get("imported_from")) |v| v == .string and std.mem.eql(u8, v.string, "claude") else false;
const strict = if (obj.get("strict")) |v| (v == .bool and v.bool) else false;
const ultracode_mode = if (obj.get("ultracode_mode")) |v| (v == .bool and v.bool) else false;
const goal: ?agent_mod.Goal = if (obj.get("goal")) |v| goalFromValue(v, unixMs(root.io)) else null;
@@ -493,8 +494,14 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8
if (promptCacheKeyFromSession(obj)) |k| http_headers.restoreProjectRootId(k);
root.ensureStoredKeys(keys);
- if (std.mem.eql(u8, pid, "codex")) root.ensureModelCatalog(keys.*);
- root.provider = try keys.providerById(pid, model);
+ if (!claude_import) {
+ if (std.mem.eql(u8, pid, "codex")) root.ensureModelCatalog(keys.*);
+ root.provider = try keys.providerById(pid, model);
+ } else {
+ // The source route is metadata. Import history into the configured
+ // graff provider without resolving any credentials for Claude Code.
+ msgs = try @import("adopt_conversation.zig").forProvider(arena, msgs, root.provider.kind);
+ }
// A resumed session may use a different wire format than the startup
// default. Materialize that catalog before rebasing its saved context
// meter, and keep every still-unused format lazy.