Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
feat: one install sets up the laptop's other repos
Shrish Dwivedie17f37611886
diff --git a/src/cloud/other-repos.ts b/src/cloud/other-repos.tsnew file mode 100644index 00000000..0f2c99cd--- /dev/null+++ b/src/cloud/other-repos.ts@@ -0,0 +1,149 @@+/**+ * The other repos on this laptop, for one install to reach all of them. After+ * the first repo is connected, Trail's onboarding page lists the repos Claude+ * Code ran in here (their names only, never their paths), the person ticks the+ * ones they want, and this sets each one up the way the first was: agents+ * wired, the map built, the repo added to the workspace and its learnings+ * synced. Only places Claude Code already ran in, or Trail already knows, are+ * looked at: nothing searches the disk.+ */+import { spawn } from "node:child_process";+import { existsSync, lstatSync, readdirSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";+import { graftCliPath } from "../claude/paths.js";+import { firstCwd } from "../init/transcript.js";+import { knownRepos, remoteKey, repoName } from "../notes/home.js";+import { syncRepo } from "./workspace-sync.js";+import { addRepo, fetchMachinePicks, isError, postRepoSetup, type Cloud } from "./workspace.js";++/** At most this many go to the page, most recently used first. */+export const OTHER_REPOS_MAX = 15;++export interface OtherRepo {+ key: string;+ name: string;+ /** The checkout to set up; stays on this laptop. */+ checkout: string;+ /** When Claude Code (or Trail) last ran there, in ms; 0 when unknown. */+ lastUsed: number;+ /** Claude Code sessions run there. */+ sessions: number;+}++/**+ * Repos with a remote that Claude Code ran in (by each project folder's first+ * transcript) or Trail ran in, besides `exceptKey`, deduped by remote.+ */+export function otherRepos(exceptKey: string, home: string = homedir(), env: NodeJS.ProcessEnv = process.env): OtherRepo[] {+ const byKey = new Map<string, OtherRepo>();+ const add = (cwd: string, lastUsed: number, sessions: number) => {+ if (!cwd || cwd === home || !existsSync(cwd)) return;+ const found = remoteKey(cwd);+ if (!found || found.key === exceptKey) return;+ const had = byKey.get(found.key);+ if (!had) {+ byKey.set(found.key, { key: found.key, name: repoName(found.key, found.checkout), checkout: found.checkout, lastUsed, sessions });+ return;+ }+ had.sessions += sessions;+ if (lastUsed > had.lastUsed) Object.assign(had, { lastUsed, checkout: found.checkout });+ };++ const projects = join(home, ".claude", "projects");+ let folders: string[] = [];+ try {+ folders = readdirSync(projects);+ } catch {+ /* no Claude Code here */+ }+ for (const folder of folders) {+ const dir = join(projects, folder);+ let files: { name: string; mtimeMs: number }[];+ try {+ // A linked folder can bring in someone else's sessions: left out, as init does.+ if (!lstatSync(dir).isDirectory()) continue;+ files = readdirSync(dir)+ .filter((f) => f.endsWith(".jsonl"))+ .map((name) => ({ name, st: lstatSync(join(dir, name)) }))+ .filter((f) => f.st.isFile())+ .map((f) => ({ name: f.name, mtimeMs: f.st.mtimeMs }));+ } catch {+ continue;+ }+ if (!files.length) continue;+ files.sort((a, b) => a.name.localeCompare(b.name));+ const cwd = firstCwd(join(dir, files[0].name));+ if (cwd) add(cwd, Math.max(...files.map((f) => f.mtimeMs)), files.length);+ }+ for (const r of knownRepos(env)) if (r.path) add(r.path, r.seenAt, 0);++ return [...byKey.values()].sort((a, b) => b.lastUsed - a.lastUsed).slice(0, OTHER_REPOS_MAX);+}++/** What the page gets: names and counts only. */+export function machinePayload(repos: OtherRepo[]): { key: string; name: string; last_used?: string; sessions: number }[] {+ return repos.map((r) => ({ key: r.key, name: r.name, sessions: r.sessions, ...(r.lastUsed ? { last_used: new Date(r.lastUsed).toISOString() } : {}) }));+}++export interface SetupOptions {+ fetchImpl?: typeof fetch;+ sleep?: (ms: number) => Promise<void>;+ /** Stop waiting for the person's pick. */+ late: () => boolean;+ /** Wires agents and builds the map in a checkout; `trail init --yes` by default. */+ initRepo?: (checkout: string) => Promise<boolean>;+}++/**+ * Wait for the person to pick, then set each picked repo up in turn, saying+ * how each goes. Returns the keys that are now in the workspace.+ */+export async function setUpPicked(cloud: Cloud, state: string, repos: OtherRepo[], opts: SetupOptions): Promise<string[]> {+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));+ let picks: string[] | null = null;+ for (;;) {+ const got = await fetchMachinePicks(cloud, state, opts.fetchImpl);+ if (!isError(got) && got.picks) {+ picks = got.picks;+ break;+ }+ if (isError(got) && got.status === 404) return [];+ if (opts.late()) return [];+ await sleep(2000);+ }++ const added: string[] = [];+ let repoKeys = [...cloud.repos];+ for (const key of picks) {+ const r = repos.find((x) => x.key === key);+ if (!r) continue;+ await postRepoSetup(cloud, state, key, "setting_up", 0, opts.fetchImpl);+ let learnings = -1;+ if (await (opts.initRepo ?? initRepo)(r.checkout)) {+ const res = await addRepo(cloud, { key: r.key, name: r.name }, opts.fetchImpl);+ if (!isError(res)) {+ repoKeys = [...new Set([...repoKeys, ...res.repos.map((x) => x.key)])];+ const synced = await syncRepo(r.checkout, { ...cloud, repos: repoKeys }, { fetch: false, fetchImpl: opts.fetchImpl });+ if (!isError(synced)) learnings = synced.learnings;+ }+ }+ if (learnings >= 0) added.push(key);+ await postRepoSetup(cloud, state, key, learnings >= 0 ? "done" : "failed", Math.max(learnings, 0), opts.fetchImpl);+ }+ return added;+}++/** `trail init --yes` in the checkout, quietly, without reading past sessions again. */+function initRepo(checkout: string): Promise<boolean> {+ return new Promise((done) => {+ const child = spawn(process.execPath, [graftCliPath(), "init", checkout, "--yes", "--plain"], {+ cwd: checkout,+ stdio: "ignore",+ windowsHide: true,+ env: { ...process.env, TRAIL_NO_LOOK_BACK: "1" },+ });+ child.on("error", () => done(false));+ child.on("exit", (code) => done(code === 0));+ });+}diff --git a/src/cloud/pair.ts b/src/cloud/pair.tsindex 77fef08d..650461bc 100644--- a/src/cloud/pair.ts+++ b/src/cloud/pair.ts@@ -22,7 +22,8 @@ import { skillName } from "../skills/skills.js";import { newState } from "./nudge.js";import type { TeammateSummary, TokensSummary } from "./onboarding.js";import { dropActivity, reviewPayload, syncRepo } from "./workspace-sync.js";-import { claimHandoff, fetchMe, isError, postHandoffProgress, readCloud, registerHandoff, trailUrl, writeCloud, type Cloud } from "./workspace.js";+import { machinePayload, otherRepos, setUpPicked, type OtherRepo } from "./other-repos.js";+import { claimHandoff, fetchMe, isError, postHandoffProgress, readCloud, registerHandoff, sendMachineRepos, trailUrl, writeCloud, type Cloud } from "./workspace.js";/** A pair code as the onboarding page prints it: letters and digits. */export function validPairCode(code: string): boolean {@@ -243,10 +244,16 @@ export interface FinishOptions {now?: () => number;/** How long to wait for the person, all told. */waitMs?: number;+ /** The laptop's other repos to offer; found from Claude Code's sessions by default. */+ otherRepos?: (exceptKey: string) => OtherRepo[];+ /** Sets up a picked repo's agents and map; `trail init --yes` by default. */+ initRepo?: (checkout: string) => Promise<boolean>;}/** Wait an hour at most for someone to sign up, connect and review. */const FINISH_WAIT_MS = 60 * 60 * 1000;+/** Once the review is in, how much longer to wait for a pick of the other repos. */+const PICK_AFTER_REVIEW_MS = 10 * 60 * 1000;/*** What `_trail-pair` runs: wait for the person to connect in the browser, save@@ -275,10 +282,24 @@ export async function finishPair(state: string, repo: string, opts: FinishOptionawait sleep(1500);}+ // The laptop's other repos go to the page by name; the ones the person+ // picks are set up while they carry on, alongside the review below.+ const place = repoPlace(repo);+ const others = (opts.otherRepos ?? otherRepos)(place.key);+ const offered = await sendMachineRepos(cloud, state, machinePayload(others), opts.fetchImpl);+ let reviewedAt = 0;+ const pickLate = () => late() || (reviewedAt > 0 && now() - reviewedAt >= PICK_AFTER_REVIEW_MS);+ const extra = !isError(offered) && others.length+ ? setUpPicked(cloud, state, others, { fetchImpl: opts.fetchImpl, sleep, late: pickLate, initRepo: opts.initRepo }).catch(() => [] as string[])+ : Promise.resolve([] as string[]);+// Trail turns progress away once the review is in: that's the signal.for (;;) {const r = await postHandoffProgress(base, { state }, opts.fetchImpl);- if (r === "reviewed") break;+ if (r === "reviewed") {+ reviewedAt = now();+ break;+ }if (r === "gone") return "expired";if (late()) return "timed_out";await sleep(2000);@@ -290,8 +311,11 @@ export async function finishPair(state: string, repo: string, opts: FinishOptioncloud = { ...cloud, user: me.user, workspace: me.workspace, repos: me.repos.map((r) => r.key) };writeCloud(cloud);}- const place = repoPlace(repo);- if (!place.git) return "uploaded";- const res = await syncRepo(place.checkout, readCloud() ?? cloud, { fetch: false, fetchImpl: opts.fetchImpl });- return isError(res) ? "failed" : "uploaded";+ const res = place.git ? await syncRepo(place.checkout, readCloud() ?? cloud, { fetch: false, fetchImpl: opts.fetchImpl }) : null;+ // The picked repos joined the workspace too: save them with the rest.+ if ((await extra).length) {+ const after = await fetchMe(cloud, opts.fetchImpl);+ if (!isError(after)) writeCloud({ ...(readCloud() ?? cloud), repos: after.repos.map((r) => r.key) });+ }+ return res && isError(res) ? "failed" : "uploaded";}diff --git a/src/cloud/workspace.ts b/src/cloud/workspace.tsindex 2cc6ff9b..bb2c1f24 100644--- a/src/cloud/workspace.ts+++ b/src/cloud/workspace.ts@@ -279,6 +279,21 @@ export function addRepo(c: Cloud, repo: { key: string; name: string }, fetchImplreturn authed<{ repos: WorkspaceRepo[] }>(c, "POST", "/api/cli/repos", repo, { fetchImpl });}+/** The laptop's other repos, by name only, for the onboarding page to offer. */+export function sendMachineRepos(c: Cloud, state: string, repos: { key: string; name: string; last_used?: string; sessions: number }[], fetchImpl?: Fetch): Promise<object | ApiError> {+ return authed<object>(c, "POST", "/api/cli/handoffs/repos", { state, repos }, { fetchImpl });+}++/** Which of them the person picked: null until they choose. */+export function fetchMachinePicks(c: Cloud, state: string, fetchImpl?: Fetch): Promise<{ picks: string[] | null } | ApiError> {+ return authed<{ picks: string[] | null }>(c, "POST", "/api/cli/handoffs/picks", { state }, { fetchImpl });+}++/** How setting up one picked repo is going, for the page. */+export function postRepoSetup(c: Cloud, state: string, key: string, status: "setting_up" | "done" | "failed", learnings = 0, fetchImpl?: Fetch): Promise<object | ApiError> {+ return authed<object>(c, "POST", "/api/cli/handoffs/repos/status", { state, key, status, learnings }, { fetchImpl });+}+export interface UploadedLearning {/** `.trail/learnings/<name>`, or `.claude/skills/<name>/SKILL.md` for a skill. */path: string;diff --git a/test/trail-other-repos.test.ts b/test/trail-other-repos.test.tsnew file mode 100644index 00000000..e8f878e9--- /dev/null+++ b/test/trail-other-repos.test.ts@@ -0,0 +1,174 @@+/**+ * One install, every repo: after the first repo connects, the laptop's other+ * repos (the ones Claude Code ran in) go to the onboarding page by name, and+ * the ones the person picks are set up and added to the workspace.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { mkdirSync, mkdtempSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { BRAND_ENV } from "../src/brand.js";+import { writeNote } from "../src/notes/notes.js";+import { finishPair } from "../src/cloud/pair.js";+import { machinePayload, otherRepos } from "../src/cloud/other-repos.js";+import { readCloud } from "../src/cloud/workspace.js";+import { tmpRepo } from "./helpers.js";++process.env.DO_NOT_TRACK = "1";+process.env[BRAND_ENV] = "trail";+process.env.TRAIL_TEST_SERVER = "http://trail.test";+process.env.TRAIL_NO_FETCH = "1";++function git(d: string, args: string[]) {+ spawnSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd: d });+}++/** A repo with a GitHub remote and one committed learning. */+function repo(name: string): string {+ const dir = tmpRepo(name);+ git(dir, ["init", "-q", "-b", "main"]);+ git(dir, ["config", "user.name", "Priya Raman"]);+ git(dir, ["config", "user.email", "[email protected]"]);+ git(dir, ["remote", "add", "origin", `https://github.com/acme/${name}.git`]);+ writeNote(dir, { title: `A learning of ${name}`, body: "## Decided\nYes.", author: "Sam", date: "2026-10-07", touches: [] });+ git(dir, ["add", "-A", "-f"]);+ git(dir, ["commit", "-q", "-m", "learning"]);+ return dir;+}++/** A Claude Code project folder with `n` sessions that started in `cwd`, last touched `at`. */+function sessions(home: string, folder: string, cwd: string, n: number, at: Date): void {+ const dir = join(home, ".claude", "projects", folder);+ mkdirSync(dir, { recursive: true });+ for (let i = 0; i < n; i++) {+ const f = join(dir, `s${i}.jsonl`);+ writeFileSync(f, JSON.stringify({ type: "user", cwd, message: { role: "user", content: "hi" } }) + "\n");+ utimesSync(f, at, at);+ }+}++test("other repos come from Claude Code's sessions, by remote, newest first, never this one", () => {+ process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "other-trail-home-"));+ const home = mkdtempSync(join(tmpdir(), "other-home-"));+ const billing = repo("billing");+ const web = repo("web");+ const docs = repo("docs");+ const plain = tmpRepo("plain");+ mkdirSync(join(web, "src"));+ // Writing the learnings made them known to Trail just now: start from a Trail that knows none.+ process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "other-trail-home-"));+ sessions(home, "billing", billing, 3, new Date("2026-10-20"));+ sessions(home, "web", web, 2, new Date("2026-10-01"));+ sessions(home, "web-sub", join(web, "src"), 4, new Date("2026-10-22"));+ sessions(home, "docs", docs, 1, new Date("2026-09-01"));+ sessions(home, "plain", plain, 5, new Date("2026-10-22"));+ sessions(home, "gone", join(home, "deleted"), 5, new Date("2026-10-22"));+ // A linked folder can carry someone else's sessions: left out.+ const elsewhere = mkdtempSync(join(tmpdir(), "other-elsewhere-"));+ sessions(elsewhere, "x", docs, 9, new Date("2026-10-23"));+ symlinkSync(join(elsewhere, ".claude", "projects", "x"), join(home, ".claude", "projects", "linked"));++ const got = otherRepos("github.com/acme/billing", home);+ assert.deepEqual(got.map((r) => [r.key, r.sessions]), [["github.com/acme/web", 6], ["github.com/acme/docs", 1]]);+ assert.equal(got[0]!.checkout, web);+ assert.equal(got[0]!.name, "acme/web");+ // The page gets names and counts, never a path.+ const sent = machinePayload(got);+ assert.equal(JSON.stringify(sent).includes(tmpdir()), false);+ assert.deepEqual(Object.keys(sent[0]!).sort(), ["key", "last_used", "name", "sessions"]);+});++type Call = { method: string; path: string; body: Record<string, unknown> };++test("the picked repos are set up, added and synced, and the page hears how each went", async () => {+ process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "other-trail-home-"));+ const billing = repo("billing");+ const web = repo("web");+ const docs = repo("docs");+ const others = [+ { key: "github.com/acme/web", name: "acme/web", checkout: web, lastUsed: Date.parse("2026-10-22"), sessions: 6 },+ { key: "github.com/acme/docs", name: "acme/docs", checkout: docs, lastUsed: 0, sessions: 1 },+ ];+ const ws = { slug: "acme", name: "Acme", url: "http://trail.test/w/acme" };+ const user = { name: "Priya", email: "[email protected]" };+ let added = ["github.com/acme/billing"];+ let picksAsked = 0;+ let reviewed = false;+ const calls: Call[] = [];+ const f = (async (url: string | URL, init?: RequestInit) => {+ const c = { method: init?.method ?? "GET", path: new URL(String(url)).pathname, body: init?.body ? JSON.parse(String(init.body)) : {} };+ calls.push(c);+ const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status });+ switch (c.path) {+ case "/api/cli/handoffs/claim":+ return json(200, { token: "trl_test", user, workspace: ws, repos: [] });+ case "/api/cli/handoffs/repos":+ case "/api/cli/handoffs/repos/status":+ return json(200, {});+ case "/api/cli/handoffs/picks":+ // Not picked yet the first time.+ return json(200, { picks: ++picksAsked < 2 ? null : ["github.com/acme/web"] });+ case "/api/cli/handoffs/progress": {+ const was = reviewed;+ reviewed = picksAsked >= 2;+ return was ? json(409, { error: "reviewed" }) : json(202, {});+ }+ case "/api/cli/repos":+ added = [...added, c.body.key as string];+ return json(200, { repos: added.map((key) => ({ key, name: key, learnings: 0, added_by: "Priya" })) });+ case "/api/cli/me":+ return json(200, { user, workspace: ws, repos: added.map((key) => ({ key, name: key, learnings: 0, added_by: "Priya" })) });+ case "/api/cli/learnings":+ return json(200, { learnings: 1, added: 1 });+ }+ return json(404, { error: "not found" });+ }) as typeof fetch;++ const inited: string[] = [];+ const outcome = await finishPair("s".repeat(32), billing, {+ fetchImpl: f,+ sleep: async () => {},+ otherRepos: () => others,+ initRepo: async (dir) => (inited.push(dir), true),+ });+ assert.equal(outcome, "uploaded");++ const sent = calls.find((c) => c.path === "/api/cli/handoffs/repos")!;+ assert.deepEqual((sent.body.repos as { key: string }[]).map((r) => r.key), ["github.com/acme/web", "github.com/acme/docs"]);+ assert.deepEqual(inited, [web], "only the picked repo is set up");+ const statuses = calls.filter((c) => c.path === "/api/cli/handoffs/repos/status").map((c) => [c.body.key, c.body.status, c.body.learnings]);+ assert.deepEqual(statuses, [["github.com/acme/web", "setting_up", 0], ["github.com/acme/web", "done", 1]]);+ const uploads = calls.filter((c) => c.path === "/api/cli/learnings").map((c) => (c.body.repo as { key: string }).key);+ assert.deepEqual(uploads.sort(), ["github.com/acme/billing", "github.com/acme/web"]);+ assert.deepEqual(readCloud()?.repos.sort(), ["github.com/acme/billing", "github.com/acme/web"]);+});++test("a repo that fails to set up says so and isn't added", async () => {+ process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "other-trail-home-"));+ const billing = repo("billing");+ const web = repo("web");+ const calls: Call[] = [];+ let progress = 0;+ const f = (async (url: string | URL, init?: RequestInit) => {+ const c = { method: init?.method ?? "GET", path: new URL(String(url)).pathname, body: init?.body ? JSON.parse(String(init.body)) : {} };+ calls.push(c);+ const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status });+ if (c.path === "/api/cli/handoffs/claim") return json(200, { token: "t", user: { name: "P", email: "[email protected]" }, workspace: { slug: "a", name: "A", url: "x" }, repos: [] });+ if (c.path === "/api/cli/handoffs/picks") return json(200, { picks: ["github.com/acme/web"] });+ if (c.path === "/api/cli/handoffs/progress") return ++progress > 1 ? json(409, {}) : json(202, {});+ if (c.path === "/api/cli/me") return json(200, { user: { name: "P", email: "[email protected]" }, workspace: { slug: "a", name: "A", url: "x" }, repos: [{ key: "github.com/acme/billing", name: "b", learnings: 0, added_by: "P" }] });+ if (c.path === "/api/cli/learnings") return json(200, { learnings: 1, added: 0 });+ return json(200, {});+ }) as typeof fetch;+ await finishPair("s".repeat(32), billing, {+ fetchImpl: f,+ sleep: async () => {},+ otherRepos: () => [{ key: "github.com/acme/web", name: "acme/web", checkout: web, lastUsed: 0, sessions: 1 }],+ initRepo: async () => false,+ });+ const statuses = calls.filter((c) => c.path === "/api/cli/handoffs/repos/status").map((c) => c.body.status);+ assert.deepEqual(statuses, ["setting_up", "failed"]);+ assert.equal(calls.some((c) => c.path === "/api/cli/repos"), false);+});diff --git a/test/trail-pair.test.ts b/test/trail-pair.test.tsindex a18d3154..a99e7644 100644--- a/test/trail-pair.test.ts+++ b/test/trail-pair.test.ts@@ -122,7 +122,7 @@ test("the child waits for the connect, then the review, and only then uploads",if (c.path === "/api/cli/learnings") return { status: 200, body: { learnings: 1, added: 0 } };return { status: 404, body: { error: "not found" } };});- const outcome = await finishPair("s".repeat(32), dir, { fetchImpl: t.fetch, sleep: async () => {} });+ const outcome = await finishPair("s".repeat(32), dir, { fetchImpl: t.fetch, sleep: async () => {}, otherRepos: () => [] });assert.equal(outcome, "uploaded");const order = t.calls.map((c) => c.path);@@ -137,7 +137,7 @@ test("the child waits for the connect, then the review, and only then uploads",test("an expired link stops the child without uploading", async () => {freshHome();const t = fakeTrail(() => ({ status: 410, body: { error: "gone" } }));- const outcome = await finishPair("s".repeat(32), repo(), { fetchImpl: t.fetch, sleep: async () => {} });+ const outcome = await finishPair("s".repeat(32), repo(), { fetchImpl: t.fetch, sleep: async () => {}, otherRepos: () => [] });assert.equal(outcome, "expired");assert.equal(t.calls.some((c) => c.path === "/api/cli/learnings"), false);});