Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

feat(cloud): trail init --pair streams setup to Trail's onboarding page

Shrish Dwivediabd28c31f926
diff --git a/src/cli.ts b/src/cli.ts
index bac6a570..d8d1586c 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -61,6 +61,7 @@ import { costLabel, listNotes, noteName, notePlace, noteTargets, readingTokens,
import { aboutTerms, currentSessionCost } from "./notes/session-cost.js";
import { beginPastRead, finishPastRead, type Finding } from "./notes/cold-start.js";
import { beginReviewRead, finishReviewRead, type ReviewFinding } from "./notes/pr-reviews.js";
+import { finishPair, PairRun, validPairCode } from "./cloud/pair.js";
import { currentBranch, noteAuthor, teammatesOn } from "./notes/git-facts.js";
import { confirm, fold, getSkill, learn, listSkills, publish, skillForAgent, skillName, skillStatus, type LearnResult } from "./skills/skills.js";
import { clearPending, cloudLines, loginLink, sessionKey, waitForConnect } from "./cloud/nudge.js";
@@ -365,6 +366,15 @@ program
await waitForConnect();
});
+program
+ .command("_trail-pair", { hidden: true })
+ .description("internal: after `init --pair`, wait for the connect and the review in the browser, then upload the repo's learnings")
+ .argument("<state>")
+ .argument("<dir>")
+ .action(async (state: string, dir: string) => {
+ await finishPair(state, resolve(dir));
+ });
+
program
.command("_update-check", { hidden: true })
.description("internal: refresh the cached latest-version answer")
@@ -1318,7 +1328,8 @@ grouped(program.command("init"), GROUP.setup)
"--connect <code>",
"connect this machine to your Trail workspace with the one-time code from app.trailhq.com, and send it a summary of this repo (titles, counts and names; never code)",
)
- .option("--server <url>", "with --connect: the Trail to connect to, e.g. https://dev.trailhq.com or http://localhost:5173 (default: TRAIL_URL, else https://app.trailhq.com)")
+ .option("--pair <code>", "the pair code from Trail's onboarding page: that page shows this run live, then you review what it found")
+ .option("--server <url>", "the Trail that gave the code (default: Trail cloud)")
.action(async (dir: string, opts: InitOptions) => {
if (opts.connect !== undefined) await runConnectInit(dir, opts);
else await runInitCommand(dir, opts);
@@ -1446,7 +1457,7 @@ function printLines(lines: string[]): void {
}
/** `graft init`'s flags, as commander hands them over. */
-interface InitOptions { build?: boolean; agents?: string[]; allAgents?: boolean; listAgents?: boolean; mcp?: boolean; hooks?: boolean; statusline?: boolean; dryRun?: boolean; yes?: boolean; global?: boolean; verbose?: boolean; connect?: string; server?: string }
+interface InitOptions { build?: boolean; agents?: string[]; allAgents?: boolean; listAgents?: boolean; mcp?: boolean; hooks?: boolean; statusline?: boolean; dryRun?: boolean; yes?: boolean; global?: boolean; verbose?: boolean; connect?: string; pair?: string; server?: string }
/** What `init --connect` hears from a run of init, as it happens: the stages the web page ticks off. */
interface InitProgress {
@@ -1460,6 +1471,9 @@ function shown(repo: string, path: string): string {
return relative(repo, path).split("\\").join("/");
}
+/** Agents init knows by another id: both read AGENTS.md. */
+const AGENT_ALIASES: Record<string, string> = { codex: "agents", opencode: "agents" };
+
/** `graft init`. */
async function runInitCommand(dir: string, opts: InitOptions, progress?: InitProgress): Promise<{ ids: string[] } | null> {
if (opts.listAgents) {
@@ -1467,7 +1481,10 @@ async function runInitCommand(dir: string, opts: InitOptions, progress?: InitPro
return null;
}
const repo = resolve(dir);
- const explicit = Array.isArray(opts.agents) ? opts.agents : undefined;
+ // Codex and OpenCode read AGENTS.md: `--agents codex` means that wiring.
+ // The name as given is kept for Trail's onboarding page.
+ const asked = Array.isArray(opts.agents) ? opts.agents : undefined;
+ const explicit = asked ? [...new Set(asked.map((id) => AGENT_ALIASES[id] ?? id))] : undefined;
// Checked before anything is written: run from the home folder, init wired
// it, mapped every code file under it, then said to commit.
@@ -1550,6 +1567,33 @@ async function runInitCommand(dir: string, opts: InitOptions, progress?: InitPro
return null;
}
+ // With --pair, Trail's onboarding page is waiting on this run: tell it
+ // first, so the person can sign up while the rest of init runs.
+ let pair: PairRun | null = null;
+ if (opts.pair !== undefined) {
+ const server = opts.server?.trim().replace(/\/+$/, "");
+ if (server) {
+ if (!/^https?:\/\//.test(server)) {
+ console.error("✗ --server takes a URL, like https://trail.acme.internal");
+ process.exitCode = 1;
+ return null;
+ }
+ process.env.TRAIL_URL = server;
+ }
+ if (!validPairCode(opts.pair)) {
+ console.error(`✗ --pair takes the code from Trail's onboarding page, got "${opts.pair}"`);
+ process.exitCode = 1;
+ return null;
+ }
+ const started = await PairRun.start(repo, opts.pair, { agent: asked?.[0] ?? ids[0]!, version: currentVersion });
+ if ("error" in started) {
+ console.error(`⚠ couldn't tell Trail about this run (${started.error}); setting up here anyway`);
+ } else {
+ pair = started;
+ console.error(`· Trail's page is following along · ${started.url}`);
+ }
+ }
+
const wantClaude = ids.includes("claude");
const cliPath = fileURLToPath(import.meta.url);
@@ -1575,6 +1619,12 @@ async function runInitCommand(dir: string, opts: InitOptions, progress?: InitPro
if (pastRead) console.error(`· reading your ${pastRead.sessions} past Claude sessions here for what you keep telling Claude`);
const reviewRead = TRAIL && wantClaude ? beginReviewRead(repo) : null;
if (reviewRead) console.error("· reading review comments on this repo's merged PRs for what reviewers keep flagging");
+ if (pair) {
+ if (pastRead) pair.phase("decisions", "running", "", `Reading ${pastRead.sessions} past Claude sessions`);
+ else pair.phase("decisions", "done", "none here");
+ if (reviewRead) pair.phase("prs", "running", "", "Reading review comments on merged PRs");
+ else pair.phase("prs", "done", "none here");
+ }
if (children.length)
console.error(`· workspace: wiring ${repo} and ${children.length} child repo(s) — ${children.join(", ")}`);
@@ -1592,7 +1642,12 @@ async function runInitCommand(dir: string, opts: InitOptions, progress?: InitPro
// the workspace build, so it covers every child.
let graphLine: string | null = null;
if (!verbose) {
+ pair?.phase("files", "running", "", "Mapping the code");
const res = await buildGraphWithProgress(repo, { build: opts.build, cliPath });
+ if (pair) {
+ const files = res.graph?.files;
+ pair.phase("files", "done", files ? `${files.toLocaleString("en-US")} files` : "", files ? `Mapped ${files.toLocaleString("en-US")} files` : "Mapped the code");
+ }
for (const m of res.messages) console.error(m);
const existing = res.built ? null : loadGraphCached(contextDirFor(repo, children.length ? undefined : program.opts<GlobalOpts>().dir));
const fmt = (x: number) => x.toLocaleString("en-US");
@@ -1647,7 +1702,7 @@ async function runInitCommand(dir: string, opts: InitOptions, progress?: InitPro
// sources, all ticked to start; a scripted run, or one with --yes, keeps
// them all. Cancelling saves none, and the next init asks again.
const picked =
- process.stdin.isTTY && process.stderr.isTTY && !opts.yes && fromSessions.length + fromReviews.length
+ process.stdin.isTTY && process.stderr.isTTY && !opts.yes && !pair && fromSessions.length + fromReviews.length
? await pickLearnings([
...fromSessions.map((f) => ({ title: f.title, forTeam: f.for === "team", sessions: f.sessions.length })),
...fromReviews.map((f) => ({ title: f.title, forTeam: true, prs: f.prs.length })),
@@ -1667,6 +1722,7 @@ async function runInitCommand(dir: string, opts: InitOptions, progress?: InitPro
sessionsRead = result.read ?? 0;
saved.forEach((note, i) => learnedFrom.push({ note, sessions: kept[i]?.sessions.length }));
const offered = result.findings.length;
+ pair?.phase("decisions", "done", `${result.read} sessions`, `Read ${result.read} past sessions: ${saved.length} thing${saved.length === 1 ? "" : "s"} you told Claude more than once`);
if (saved.length) {
const n = saved.length;
const what = n < offered ? `kept ${n} of the ${offered} things` : `learned ${n} thing${n === 1 ? "" : "s"}`;
@@ -1689,6 +1745,7 @@ async function runInitCommand(dir: string, opts: InitOptions, progress?: InitPro
if (reviewRead) {
const { result, saved, kept, cancelled } = await finishReviewRead(repo, reviewRead, keepFrom<ReviewFinding>(fromSessions.length));
const offered = result.findings.length;
+ pair?.phase("prs", "done", `${result.prs} PRs`, `Read ${result.prs} merged PRs: ${saved.length} thing${saved.length === 1 ? "" : "s"} reviewers flagged more than once`);
if (saved.length) {
const n = saved.length;
const what = n < offered ? `kept ${n} of the ${offered} things` : `learned ${n} thing${n === 1 ? "" : "s"}`;
@@ -1768,6 +1825,15 @@ async function runInitCommand(dir: string, opts: InitOptions, progress?: InitPro
edges: graphs.reduce((n, g) => n + g.meta.edgeCount, 0),
}),
);
+ // Hand what was found to the review page, and leave a child waiting for
+ // the person to connect and review there.
+ if (pair) {
+ await pair.finish(repo);
+ pair.handOff(repo);
+ console.error(`✓ Trail has what it found · review it in the browser: ${pair.url}`);
+ if (!process.stdout.isTTY) console.error(`[trail] Tell the user, in one line: their Trail page has moved on; review what Trail found there. If it isn't open, the link is ${pair.url}`);
+ }
+
// Sorted so `claude,cursor` and `cursor,claude` aggregate as one value.
track(
"init_completed",
diff --git a/src/cloud/pair.ts b/src/cloud/pair.ts
new file mode 100644
index 00000000..c53be9ee
--- /dev/null
+++ b/src/cloud/pair.ts
@@ -0,0 +1,195 @@
+/**
+ * `trail init --pair CODE`: the setup prompt a person copied from Trail's
+ * onboarding page carries a pair code. With it, init tells Trail about itself
+ * before doing anything slow, so the page the person is on moves on to sign-up
+ * at once; then it streams what it's doing (the map, the PRs, past sessions,
+ * the learnings it wrote) to the page that shows it live, and hands over what
+ * it found for the person to review there.
+ *
+ * Nothing goes up as a workspace learning from here. The person keeps or drops
+ * each one on the review page, and Trail stores that. A detached
+ * `_trail-pair` child then waits for the connection, saves it, waits for the
+ * review, and uploads the repo the usual way, which leaves a dropped learning
+ * dropped.
+ */
+import { spawn } from "node:child_process";
+import { graftCliPath } from "../claude/paths.js";
+import { noteAuthor } from "../notes/git-facts.js";
+import { repoName, repoPlace } from "../notes/home.js";
+import { newState, pickerRepos } from "./nudge.js";
+import { dropActivity, learningsPayload, syncRepo } from "./workspace-sync.js";
+import { claimHandoff, fetchMe, isError, postHandoffProgress, readCloud, registerHandoff, 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 {
+ return /^[A-Za-z0-9-]{6,64}$/.test(code.trim());
+}
+
+export type PhaseId = "install" | "files" | "prs" | "decisions" | "learnings";
+type PhaseStatus = "todo" | "running" | "done";
+interface Phase {
+ id: PhaseId;
+ label: string;
+ status: PhaseStatus;
+ count: string;
+}
+
+/** The most found learnings one progress call may carry. */
+const FOUND_PER_CALL = 200;
+
+/**
+ * One init run, reported to the onboarding page. Every call is best effort:
+ * a slow or unreachable Trail never holds up or fails init.
+ */
+export class PairRun {
+ readonly state: string;
+ readonly url: string;
+ private readonly base: string;
+ private phases: Phase[];
+ private chain: Promise<unknown> = Promise.resolve();
+ private readonly fetchImpl?: typeof fetch;
+
+ private constructor(base: string, state: string, url: string, version: string, fetchImpl?: typeof fetch) {
+ this.base = base;
+ this.fetchImpl = fetchImpl;
+ this.state = state;
+ this.url = url;
+ this.phases = [
+ { id: "install", label: "Install Trail-code", status: "done", count: version },
+ { id: "files", label: "Map the code", status: "todo", count: "" },
+ { id: "prs", label: "Read pull request reviews", status: "todo", count: "" },
+ { id: "decisions", label: "Read past Claude sessions", status: "todo", count: "" },
+ { id: "learnings", label: "Write learnings", status: "todo", count: "" },
+ ];
+ }
+
+ /**
+ * Tell Trail about this run, with the pair code, and return it; null when
+ * Trail can't be reached or turns the code down (init carries on without it).
+ */
+ static async start(repo: string, code: string, opts: { agent: string; version: string; fetchImpl?: typeof fetch }): Promise<PairRun | { error: string }> {
+ const base = trailUrl();
+ const state = newState();
+ const place = repoPlace(repo);
+ const current = place.git ? { key: place.key, name: repoName(place.key, place.checkout) } : null;
+ // This repo first, with the learnings it already has: init hasn't told
+ // Trail about it yet, so the list of known repos may not have it.
+ const here = place.git ? learningsPayload(place.checkout).filter((l) => l.ref === "").length : 0;
+ const known = pickerRepos().filter((r) => r.key !== current?.key);
+ if (current) known.unshift({ ...current, learnings: here });
+ const reg = await registerHandoff(
+ base,
+ { state, repo: current, repos: known, author: noteAuthor(repo), pair: code.trim().toUpperCase() },
+ opts.fetchImpl,
+ );
+ if (isError(reg)) return { error: reg.error };
+ const run = new PairRun(base, state, reg.url, opts.version, opts.fetchImpl);
+ run.send({ agent: opts.agent, phases: run.phases, log: [`Installed Trail-code ${opts.version}`] });
+ return run;
+ }
+
+ /** Move a step on: running, or done with what it counted. */
+ phase(id: PhaseId, status: PhaseStatus, count = "", log?: string): void {
+ this.phases = this.phases.map((p) => (p.id === id ? { ...p, status, count: count || p.count } : p));
+ this.send({ phases: this.phases, ...(log ? { log: [log] } : {}) });
+ }
+
+ /** Hand over the repo's learnings for review, then say the read is done. */
+ finish(repo: string): Promise<void> {
+ const place = repoPlace(repo);
+ const found = place.git
+ ? learningsPayload(place.checkout)
+ .filter((l) => l.ref === "")
+ .map((l) => ({ path: l.path, title: l.title, author: l.author, body: l.body, hash: l.hash, touches: l.touches }))
+ : [];
+ const n = found.length;
+ this.phases = this.phases.map((p) => (p.status === "done" ? p : { ...p, status: "done" as const }));
+ this.phases = this.phases.map((p) => (p.id === "learnings" ? { ...p, count: String(n) } : p));
+ for (let i = 0; i < Math.max(n, 1); i += FOUND_PER_CALL) {
+ const part = found.slice(i, i + FOUND_PER_CALL);
+ this.send({ phases: this.phases, found: part, ...(i === 0 ? { log: [`Found ${n} learning${n === 1 ? "" : "s"} for your team`] } : {}) });
+ }
+ this.send({ done: true });
+ return this.flush();
+ }
+
+ /** Wait for every report so far to be sent (or to fail). */
+ flush(): Promise<void> {
+ return this.chain.then(() => undefined);
+ }
+
+ /** Start the detached wait for the connection and the review. */
+ handOff(repo: string): void {
+ const child = spawn(process.execPath, [graftCliPath(), "_trail-pair", this.state, repo], {
+ detached: true,
+ stdio: "ignore",
+ windowsHide: true,
+ env: { ...process.env, TRAIL_URL: this.base },
+ });
+ child.unref();
+ }
+
+ private send(body: Record<string, unknown>): void {
+ // One after another, so the page sees the steps in order.
+ this.chain = this.chain.then(() => postHandoffProgress(this.base, { state: this.state, ...body }, this.fetchImpl)).catch(() => undefined);
+ }
+}
+
+export interface FinishOptions {
+ fetchImpl?: typeof fetch;
+ sleep?: (ms: number) => Promise<void>;
+ now?: () => number;
+ /** How long to wait for the person, all told. */
+ waitMs?: number;
+}
+
+/** Wait an hour at most for someone to sign up, connect and review. */
+const FINISH_WAIT_MS = 60 * 60 * 1000;
+
+/**
+ * What `_trail-pair` runs: wait for the person to connect in the browser, save
+ * the connection, wait for their review, then upload this repo's learnings.
+ * Returns what happened, for tests.
+ */
+export async function finishPair(state: string, repo: string, opts: FinishOptions = {}): Promise<"uploaded" | "expired" | "timed_out" | "failed"> {
+ const now = opts.now ?? Date.now;
+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
+ const started = now();
+ const late = () => now() - started >= (opts.waitMs ?? FINISH_WAIT_MS);
+ const base = trailUrl();
+
+ let cloud: Cloud | null = null;
+ for (;;) {
+ const got = await claimHandoff(base, state, opts.fetchImpl);
+ if ("cloud" in got) {
+ cloud = { ...got.cloud, url: base, linkedAt: now() };
+ // Like any first connect: nothing recorded before it goes up.
+ dropActivity();
+ writeCloud(cloud);
+ break;
+ }
+ if ("error" in got) return "expired";
+ if (late()) return "timed_out";
+ await sleep(1500);
+ }
+
+ // 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 === "gone") return "expired";
+ if (late()) return "timed_out";
+ await sleep(2000);
+ }
+
+ // The review added this repo to the workspace; pick that up, then upload.
+ const me = await fetchMe(cloud, opts.fetchImpl);
+ if (!isError(me)) {
+ cloud = { ...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";
+}
diff --git a/src/cloud/workspace.ts b/src/cloud/workspace.ts
index dcfd34c1..c0fbac58 100644
--- a/src/cloud/workspace.ts
+++ b/src/cloud/workspace.ts
@@ -155,13 +155,26 @@ export interface HandoffRepo {
*/
export async function registerHandoff(
base: string,
- req: { state: string; repo: { key: string; name: string } | null; repos: HandoffRepo[]; author: string },
+ req: { state: string; repo: { key: string; name: string } | null; repos: HandoffRepo[]; author: string; pair?: string },
fetchImpl?: Fetch,
): Promise<{ url: string } | ApiError> {
const r = await call<{ url: string }>(base, "POST", "/api/cli/handoffs", req, { fetchImpl });
return isError(r) ? r : r.body;
}
+/**
+ * Report how a `trail init --pair` run is going, for the onboarding page that
+ * shows it live. "reviewed" once the person has kept or dropped what it found
+ * (Trail takes no more), "gone" when the link expired or Trail doesn't know it.
+ */
+export async function postHandoffProgress(base: string, body: { state: string } & Record<string, unknown>, fetchImpl?: Fetch): Promise<"ok" | "reviewed" | "gone" | "error"> {
+ const r = await call(base, "POST", "/api/cli/handoffs/progress", body, { fetchImpl, timeoutMs: 15_000 });
+ if (!isError(r)) return "ok";
+ if (r.status === 409) return "reviewed";
+ if (r.status === 404 || r.status === 410) return "gone";
+ return "error";
+}
+
export type ClaimResult =
| { cloud: Omit<Cloud, "url" | "linkedAt"> }
| { pending: true }
diff --git a/test/trail-pair.test.ts b/test/trail-pair.test.ts
new file mode 100644
index 00000000..c1421f8f
--- /dev/null
+++ b/test/trail-pair.test.ts
@@ -0,0 +1,139 @@
+/**
+ * `trail init --pair CODE`: init tells Trail about itself with the pair code
+ * from the onboarding page, streams its steps, and hands over the repo's
+ * learnings for review. A detached child then waits for the connection and the
+ * review before uploading, so a learning dropped on the review page stays
+ * dropped.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdtempSync } 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, PairRun, validPairCode } from "../src/cloud/pair.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_URL = "http://trail.test";
+process.env.TRAIL_NO_FETCH = "1";
+
+function freshHome(): void {
+ process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "pair-trail-home-"));
+}
+
+function git(d: string, args: string[]) {
+ spawnSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd: d });
+}
+
+/** A GitHub-backed repo with one learning in its .trail/. */
+function repo(): string {
+ const dir = tmpRepo("pair");
+ git(dir, ["init", "-q", "-b", "main"]);
+ git(dir, ["config", "user.name", "Priya Raman"]);
+ git(dir, ["remote", "add", "origin", "https://github.com/acme/billing.git"]);
+ writeNote(dir, { title: "Keep payment retries at 4", body: "## Decided\nFour retries.", author: "Sam", date: "2026-10-07", touches: [] });
+ return dir;
+}
+
+type Call = { method: string; path: string; body: Record<string, unknown> };
+
+/** A stand-in Trail: `answer` picks each response; every request is recorded. */
+function fakeTrail(answer: (c: Call, calls: Call[]) => { status: number; body?: unknown }): { fetch: typeof fetch; calls: Call[] } {
+ const calls: Call[] = [];
+ const f = (async (url: string | URL, init?: RequestInit) => {
+ const u = new URL(String(url));
+ const call = { method: init?.method ?? "GET", path: u.pathname, body: init?.body ? JSON.parse(String(init.body)) : {} };
+ calls.push(call);
+ const { status, body } = answer(call, calls);
+ return new Response(body === undefined ? "" : JSON.stringify(body), { status });
+ }) as typeof fetch;
+ return { fetch: f, calls };
+}
+
+test("pair codes are letters and digits from the onboarding page", () => {
+ assert.equal(validPairCode("X4GM5OQU4NIA65ZR"), true);
+ assert.equal(validPairCode("abc"), false);
+ assert.equal(validPairCode("rm -rf /"), false);
+});
+
+test("init --pair registers with the code, streams its steps, then hands over the learnings", async () => {
+ freshHome();
+ const dir = repo();
+ const t = fakeTrail((c) => (c.path === "/api/cli/handoffs" ? { status: 201, body: { url: "http://trail.test/connect?state=s" } } : { status: 202, body: {} }));
+ const run = await PairRun.start(dir, "x4gm5oqu4nia65zr", { agent: "codex", version: "0.23.1", fetchImpl: t.fetch });
+ assert.ok(run instanceof PairRun);
+
+ const reg = t.calls[0]!;
+ assert.equal(reg.path, "/api/cli/handoffs");
+ assert.equal(reg.body.pair, "X4GM5OQU4NIA65ZR");
+ assert.deepEqual(reg.body.repo, { key: "github.com/acme/billing", name: "acme/billing" });
+ // The repo's own learnings are counted, though init hasn't told Trail about it before.
+ assert.equal((reg.body.repos as { key: string; learnings: number }[])[0]!.learnings, 1);
+
+ run.phase("files", "running");
+ run.phase("files", "done", "12 files", "Mapped 12 files");
+ await run.finish(dir);
+
+ const progress = t.calls.filter((c) => c.path === "/api/cli/handoffs/progress");
+ assert.equal(progress[0]!.body.agent, "codex");
+ assert.ok(progress.every((c) => c.body.state === run.state));
+ const found = progress.flatMap((c) => (c.body.found as { title: string }[] | undefined) ?? []);
+ assert.deepEqual(found.map((f) => f.title), ["Keep payment retries at 4"]);
+ assert.equal(progress.at(-1)!.body.done, true);
+ // Steps arrive in the order they happened.
+ const files = progress.map((c) => (c.body.phases as { id: string; status: string }[] | undefined)?.find((p) => p.id === "files")?.status).filter(Boolean);
+ assert.deepEqual(files.slice(0, 3), ["todo", "running", "done"]);
+});
+
+test("a Trail that turns the code down leaves init to carry on", async () => {
+ freshHome();
+ const t = fakeTrail(() => ({ status: 500, body: { error: "boom" } }));
+ const run = await PairRun.start(repo(), "X4GM5OQU4NIA65ZR", { agent: "claude", version: "0.23.1", fetchImpl: t.fetch });
+ assert.ok("error" in run);
+});
+
+test("the child waits for the connect, then the review, and only then uploads", async () => {
+ freshHome();
+ const dir = repo();
+ let reviewed = false;
+ const t = fakeTrail((c, calls) => {
+ if (c.path === "/api/cli/handoffs/claim") {
+ // Waiting the first time, connected the second.
+ return calls.filter((x) => x.path === c.path).length < 2
+ ? { status: 202, body: { pending: true } }
+ : { status: 200, body: { token: "trl_test", user: { name: "Priya", email: "[email protected]" }, workspace: { slug: "acme", name: "Acme", url: "http://trail.test/w/acme" }, repos: [] } };
+ }
+ if (c.path === "/api/cli/handoffs/progress") {
+ const was = reviewed;
+ reviewed = true;
+ return was ? { status: 409, body: { error: "the learnings were already reviewed" } } : { status: 202, body: {} };
+ }
+ if (c.path === "/api/cli/me")
+ return { status: 200, body: { user: { name: "Priya", email: "[email protected]" }, workspace: { slug: "acme", name: "Acme", url: "http://trail.test/w/acme" }, repos: [{ key: "github.com/acme/billing", name: "acme/billing", learnings: 1, added_by: "Priya" }] } };
+ 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 () => {} });
+ assert.equal(outcome, "uploaded");
+
+ const order = t.calls.map((c) => c.path);
+ const firstUpload = order.indexOf("/api/cli/learnings");
+ assert.ok(firstUpload > order.lastIndexOf("/api/cli/handoffs/progress"), "no upload before the review is in");
+ const put = t.calls[firstUpload]!;
+ assert.deepEqual(put.body.repo, { key: "github.com/acme/billing", name: "acme/billing" });
+ assert.equal(readCloud()?.workspace.slug, "acme");
+ assert.deepEqual(readCloud()?.repos, ["github.com/acme/billing"]);
+});
+
+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 () => {} });
+ assert.equal(outcome, "expired");
+ assert.equal(t.calls.some((c) => c.path === "/api/cli/learnings"), false);
+});