Skip to content

Commit 243dd64

Browse files
n4mr3gclaude
andcommitted
fix(server): import agent sessions from a project's linked worktrees
Onboarding stopped offering linked worktrees in #10493 because their history belongs to the main checkout, but the import for the main checkout only accepts sessions whose cwd is the project root. Sessions that ran in a worktree were dropped entirely. Claude Code desktop runs every session in a worktree under .claude/worktrees, so most of that history never reached T3 Code. The import now also accepts sessions from linked worktrees whose commondir resolves to the project's .git directory. Imported threads keep the worktree path and branch, so resuming runs the provider in the checkout it started in. T3-managed worktrees stay excluded. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 18656a3 commit 243dd64

4 files changed

Lines changed: 152 additions & 12 deletions

File tree

‎apps/server/src/project/AgentSessionImporter.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ it.effect("imports messages once and preserves the provider native resume bindin
5757
{ role: "assistant", text: "Fixed", createdAt: "2026-09-01T10:01:00.000Z" },
5858
],
5959
},
60+
worktree: { path: "/workspace/project-feature", branch: "feature" },
6061
}),
6162
});
6263
const layerTest = AgentSessionImporter.layer.pipe(
@@ -121,6 +122,8 @@ it.effect("imports messages once and preserves the provider native resume bindin
121122
id: threadId,
122123
activeProviderThreadId: providerThread?.payload.id,
123124
historyOrigin: "v1_import",
125+
branch: "feature",
126+
worktreePath: "/workspace/project-feature",
124127
});
125128
expect(providerThread?.payload).toMatchObject({
126129
appThreadId: threadId,

‎apps/server/src/project/AgentSessionImporter.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -283,8 +283,8 @@ const make = Effect.gen(function* () {
283283
modelSelection: { instanceId: thread.providerInstanceId, model },
284284
runtimeMode: DEFAULT_RUNTIME_MODE,
285285
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
286-
branch: null,
287-
worktreePath: null,
286+
branch: outcome.worktree?.branch ?? null,
287+
worktreePath: outcome.worktree?.path ?? null,
288288
linkedPullRequest: null,
289289
branchPullRequest: null,
290290
activeProviderThreadId: providerThreadId,

‎apps/server/src/project/AgentSessionScanner.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2415,6 +2415,81 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
24152415
}),
24162416
);
24172417

2418+
it.effect("imports sessions from linked worktrees of the project with their branch", () =>
2419+
Effect.gen(function* () {
2420+
const path = yield* Path.Path;
2421+
const fileSystem = yield* FileSystem.FileSystem;
2422+
const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2423+
yield* TestClock.setTime(nowMs);
2424+
const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
2425+
const codexHomePath = yield* makeTempDir("t3code-codex-home-");
2426+
const configBaseDir = yield* makeTempDir("t3code-scanner-base-");
2427+
const repo = yield* makeTempDir("t3code-workspace-repo-");
2428+
const otherRepo = yield* makeTempDir("t3code-workspace-other-");
2429+
2430+
const addWorktree = Effect.fn("addWorktree")(function* (input: {
2431+
readonly repo: string;
2432+
readonly directory: string;
2433+
readonly name: string;
2434+
}) {
2435+
const gitDir = path.join(input.repo, ".git", "worktrees", input.name);
2436+
yield* fileSystem.makeDirectory(gitDir, { recursive: true });
2437+
yield* fileSystem.makeDirectory(input.directory, { recursive: true });
2438+
yield* fileSystem.writeFileString(path.join(gitDir, "commondir"), "../..\n");
2439+
yield* fileSystem.writeFileString(
2440+
path.join(gitDir, "HEAD"),
2441+
`ref: refs/heads/${input.name}\n`,
2442+
);
2443+
yield* fileSystem.writeFileString(
2444+
path.join(input.directory, ".git"),
2445+
`gitdir: ${gitDir}\n`,
2446+
);
2447+
});
2448+
const worktree = path.join(repo, ".claude", "worktrees", "feature");
2449+
const managedWorktree = path.join(configBaseDir, "worktrees", "repo", "managed");
2450+
const otherWorktree = path.join(otherRepo, "elsewhere");
2451+
yield* addWorktree({ repo, directory: worktree, name: "feature" });
2452+
yield* addWorktree({ repo, directory: managedWorktree, name: "managed" });
2453+
yield* addWorktree({ repo: otherRepo, directory: otherWorktree, name: "elsewhere" });
2454+
2455+
for (const [index, [sessionId, cwd]] of [
2456+
["root-session", repo],
2457+
["worktree-session", worktree],
2458+
["managed-session", managedWorktree],
2459+
["other-session", otherWorktree],
2460+
].entries()) {
2461+
yield* writeTranscript({
2462+
filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, `${sessionId}.jsonl`),
2463+
contents: `${JSON.stringify({
2464+
type: "user",
2465+
cwd,
2466+
sessionId,
2467+
message: { role: "user", content: "Fix the project" },
2468+
})}\n`,
2469+
mtimeMs: nowMs - (index + 1) * 60 * 1000,
2470+
});
2471+
}
2472+
2473+
const outcomes = yield* runRecentThreadOutcomes({
2474+
claudeHomePath,
2475+
codexHomePath,
2476+
configBaseDir,
2477+
workspaceRoot: repo,
2478+
});
2479+
2480+
expect(
2481+
outcomes.flatMap((outcome) =>
2482+
outcome._tag === "Importable"
2483+
? [{ sessionId: outcome.thread.providerSessionId, worktree: outcome.worktree }]
2484+
: [],
2485+
),
2486+
).toEqual([
2487+
{ sessionId: "root-session", worktree: null },
2488+
{ sessionId: "worktree-session", worktree: { path: worktree, branch: "feature" } },
2489+
]);
2490+
}),
2491+
);
2492+
24182493
it.effect("uses one deterministic provider instance for a shared session home", () =>
24192494
Effect.gen(function* () {
24202495
const path = yield* Path.Path;

‎apps/server/src/project/AgentSessionScanner.ts‎

Lines changed: 72 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -168,11 +168,18 @@ export interface AgentSessionThread {
168168
readonly messages: ReadonlyArray<AgentSessionThreadMessage>;
169169
}
170170

171+
/** A linked worktree of the project's repository that a session ran in. */
172+
export interface AgentSessionWorktree {
173+
readonly path: string;
174+
readonly branch: string | null;
175+
}
176+
171177
export type AgentSessionRecentThread =
172178
| {
173179
readonly _tag: "Importable";
174180
readonly thread: AgentSessionThread;
175181
readonly source: AgentSessionImportSource;
182+
readonly worktree: AgentSessionWorktree | null;
176183
}
177184
| { readonly _tag: "AlreadyImported"; readonly source: AgentSessionImportSource }
178185
| { readonly _tag: "Duplicate"; readonly source: AgentSessionImportSource }
@@ -690,15 +697,15 @@ export const make = Effect.gen(function* () {
690697
* directly instead of spawning git so a scan over hundreds of candidates
691698
* stays cheap. A `.git` file is a `gitdir:` pointer. When it points into a
692699
* `worktrees/` directory the checkout is a linked worktree, which
693-
* onboarding skips because its history belongs to the main checkout.
700+
* onboarding skips because its history imports with the main checkout.
694701
* Submodules use the same pointer shape but live under `modules/`, and
695702
* are offered like any other repository.
696703
*/
697704
const readGitIdentity = Effect.fn("AgentSessionScanner.readGitIdentity")(function* (
698705
directory: string,
699706
): Effect.fn.Return<
700707
| { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null }
701-
| { readonly _tag: "Worktree" }
708+
| { readonly _tag: "Worktree"; readonly gitDir: string }
702709
| { readonly _tag: "NotGit" }
703710
> {
704711
const gitPath = path.join(directory, ".git");
@@ -712,7 +719,9 @@ export const make = Effect.gen(function* () {
712719
const target = /^gitdir:\s*(.+)$/m.exec(pointer)?.[1]?.trim();
713720
if (target === undefined || target.length === 0) return { _tag: "NotGit" } as const;
714721
gitDir = path.resolve(directory, target);
715-
if (/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir)) return { _tag: "Worktree" } as const;
722+
if (/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir)) {
723+
return { _tag: "Worktree", gitDir } as const;
724+
}
716725
}
717726
const configText = yield* fileSystem
718727
.readFileString(path.join(gitDir, "config"))
@@ -727,6 +736,50 @@ export const make = Effect.gen(function* () {
727736
} as const;
728737
});
729738

739+
/**
740+
* Whether a session directory is the project root or a linked worktree of
741+
* the root's repository. T3-managed worktrees stay excluded because their
742+
* threads already exist.
743+
*/
744+
const matchProjectCheckout = Effect.fn("AgentSessionScanner.matchProjectCheckout")(function* (
745+
directory: string,
746+
project: { readonly identity: string; readonly gitDirIdentity: string | null },
747+
): Effect.fn.Return<
748+
| { readonly _tag: "Root" }
749+
| { readonly _tag: "Worktree"; readonly worktree: AgentSessionWorktree }
750+
| { readonly _tag: "Unrelated" }
751+
> {
752+
const resolved = path.resolve(directory);
753+
if ((yield* directoryIdentity(resolved)) === project.identity) return { _tag: "Root" } as const;
754+
if (project.gitDirIdentity === null) return { _tag: "Unrelated" } as const;
755+
const gitIdentity = yield* readGitIdentity(resolved);
756+
if (gitIdentity._tag !== "Worktree") return { _tag: "Unrelated" } as const;
757+
const realPath = yield* fileSystem
758+
.realPath(resolved)
759+
.pipe(Effect.orElseSucceed(() => resolved));
760+
if (isExcludedProjectPath(resolved) || isExcludedProjectPath(realPath)) {
761+
return { _tag: "Unrelated" } as const;
762+
}
763+
const readGitFile = (name: string) =>
764+
fileSystem.readFileString(path.join(gitIdentity.gitDir, name)).pipe(
765+
Effect.map((text) => text.trim()),
766+
Effect.orElseSucceed(() => ""),
767+
);
768+
const commonDir = yield* readGitFile("commondir");
769+
if (
770+
commonDir === "" ||
771+
(yield* directoryIdentity(path.resolve(gitIdentity.gitDir, commonDir))) !==
772+
project.gitDirIdentity
773+
) {
774+
return { _tag: "Unrelated" } as const;
775+
}
776+
const head = yield* readGitFile("HEAD");
777+
return {
778+
_tag: "Worktree",
779+
worktree: { path: resolved, branch: /^ref: refs\/heads\/(.+)$/.exec(head)?.[1] ?? null },
780+
} as const;
781+
});
782+
730783
// A large history snapshot can precede session metadata. Read bounded
731784
// chunks until a complete record names its cwd or the safety budget ends.
732785
const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* (
@@ -1331,7 +1384,15 @@ export const make = Effect.gen(function* () {
13311384
const root = path.resolve(expandHomePath(workspaceRoot, homeDir));
13321385
const realRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root));
13331386
if (isExcludedProjectPath(root) || isExcludedProjectPath(realRoot)) return Stream.empty;
1334-
const rootIdentity = yield* directoryIdentity(root);
1387+
const rootGitDir = path.join(root, ".git");
1388+
const rootGitDirStats = yield* statOption(rootGitDir);
1389+
const project = {
1390+
identity: yield* directoryIdentity(root),
1391+
gitDirIdentity:
1392+
Option.isSome(rootGitDirStats) && rootGitDirStats.value.type === "Directory"
1393+
? yield* directoryIdentity(rootGitDir, rootGitDirStats.value)
1394+
: null,
1395+
};
13351396
const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
13361397
const cutoffMs = nowMs - RECENT_THREAD_WINDOW_MS;
13371398

@@ -1345,8 +1406,7 @@ export const make = Effect.gen(function* () {
13451406
for (const candidate of candidates) {
13461407
const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
13471408
if (!path.isAbsolute(expanded)) continue;
1348-
const resolved = path.resolve(expanded);
1349-
if ((yield* directoryIdentity(resolved)) !== rootIdentity) continue;
1409+
if ((yield* matchProjectCheckout(expanded, project))._tag === "Unrelated") continue;
13501410

13511411
for (const transcript of candidate.transcripts) {
13521412
if (
@@ -1440,10 +1500,11 @@ export const make = Effect.gen(function* () {
14401500
return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
14411501
}
14421502
const expandedCwd = expandHomePath(snapshotCwd.trim(), homeDir);
1443-
if (
1444-
!path.isAbsolute(expandedCwd) ||
1445-
(yield* directoryIdentity(path.resolve(expandedCwd))) !== rootIdentity
1446-
) {
1503+
if (!path.isAbsolute(expandedCwd)) {
1504+
return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1505+
}
1506+
const checkout = yield* matchProjectCheckout(expandedCwd, project);
1507+
if (checkout._tag === "Unrelated") {
14471508
return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
14481509
}
14491510

@@ -1475,6 +1536,7 @@ export const make = Effect.gen(function* () {
14751536
_tag: "Importable",
14761537
thread: parsedThread,
14771538
source,
1539+
worktree: checkout._tag === "Worktree" ? checkout.worktree : null,
14781540
});
14791541
}).pipe(importReadLock.withPermits(1)),
14801542
),

0 commit comments

Comments
 (0)