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(trail): init --connect for the app.trailhq.com onboarding, and workspace brains over MCP
Rushabh Nagda311b9f3d230c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e1136f89..17a002ad 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,23 @@# Changelog+## Unreleased++### Added++- **`trail init --connect <code>`**: the onboarding on app.trailhq.com. The+ one-time code connects this machine to the workspace (the token goes where+ `trail login` keeps it), the page ticks off connected, mapped and learned as+ init runs, and one summary of the repo goes up: what one lookup on the code+ map saved, the learnings' titles, and teammates' recently pushed branches+ that change the files you work on. Titles, counts and names only; never+ code, diffs or session text. `--server` (or `TRAIL_URL`) points it at+ another Trail.+- **Workspace brains in your agents**: once connected, `trail mcp` also serves+ the workspace's `list_brains`, `get_context`, `search_rules` and `get_rules`,+ passed to the workspace with your token; the repo tools keep working+ offline. Claude Code gets one user-level `trail` entry that serves just+ those (`trail mcp --brains`); `trail logout` takes it out.+## 0.23.0### Changeddiff --git a/src/cli.ts b/src/cli.tsindex 8b7051e6..9c3a66e3 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -48,6 +48,7 @@ import { planInit, selectedWrites } from "./hosts/plan.js";import { planRetract, runRetract, changed, type Retraction } from "./hosts/retract.js";import { compactWrites, formatNonInteractiveHelp, formatPlan, pickLearnings, runPicker } from "./cli-picker.js";import { buildGraphWithProgress } from "./claude/build-progress.js";+import { installBrainsServer, removeBrainsServer } from "./hosts/claude-global.js";import { homedir } from "node:os";import { formatUpgradeReport, formatVersionReport, getNpmViewVersion, readCurrentVersion, readPackageName, runUpgrade } from "./cli-meta.js";import { nativeFallbackNotice } from "./graph/native.js";@@ -62,7 +63,17 @@ import { beginReviewRead, finishReviewRead, type ReviewFinding } from "./notes/pimport { 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";-import { addRepo, clearCloud, cloudEnabled, fetchMe, fetchTeam, isError, readCloud, writeCloud, type Cloud } from "./cloud/workspace.js";+import { addRepo, clearCloud, cloudEnabled, fetchMe, fetchTeam, isError, readCloud, trailUrl, writeCloud, type Cloud } from "./cloud/workspace.js";+import {+ claimConnectCode,+ learningsSummary,+ machineName,+ normalizeCode,+ OnboardingReporter,+ repoRef,+ teammatesFromGit,+ tokensOnOneLookup,+} from "./cloud/onboarding.js";import { inWorkspace, maybeSyncInBackground, recordActivity, runSyncChild, syncRepo } from "./cloud/workspace-sync.js";import type { CheckResult } from "./check/types.js";import { checkLocally } from "./check/local-check.js";@@ -957,9 +968,14 @@ program.command("mcp", { hidden: TRAIL }).description("Serve the graph over MCP (stdio) — exposes graft_find_code, graft_trace_calls, graft_find_all, graft_file_api, graft_repo_map and graft_check_freshness as tools").argument(...DIR_ARG)- .action(async (dirArg: string | undefined) => {- const dir = noteQuery(queryRoot(dirArg));+ .option("--brains", "serve only the connected Trail workspace's brain tools (what Claude Code gets after init --connect)")+ .action(async (dirArg: string | undefined, opts: { brains?: boolean }) => {const { startMcpServer } = await import("./mcp/server.js");+ if (opts.brains) {+ startMcpServer(process.cwd(), undefined, currentVersion, { brainsOnly: true });+ return;+ }+ const dir = noteQuery(queryRoot(dirArg));const globalOpts = program.opts<{ dir?: string }>();startMcpServer(dir, globalOpts.dir, currentVersion);});@@ -1295,8 +1311,14 @@ grouped(program.command("init"), GROUP.setup).option("-y, --yes", "skip the picker and wire every detected agent (the pre-0.8 default)").option("--no-global", "skip writes outside this repo (the ~/.codex/ config + hooks)").option("--verbose", "print every file written, the graph build's own output and the closing banner")+ .option(+ "--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)").action(async (dir: string, opts: InitOptions) => {- await runInitCommand(dir, opts);+ if (opts.connect !== undefined) await runConnectInit(dir, opts);+ else await runInitCommand(dir, opts);});/** Everything on stdin, or "" when nothing is piped in. */@@ -1421,7 +1443,14 @@ 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 }+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 }++/** What `init --connect` hears from a run of init, as it happens: the stages the web page ticks off. */+interface InitProgress {+ mapped?(m: { nodes: number; edges: number; files: number }): void;+ /** What init learned this run (team and personal), and how many past sessions it read; `notes` is empty when it learned nothing new. */+ learned?(l: { notes: Array<{ note: Note; sessions?: number }>; sessions: number }): void;+}/** Repo-relative with forward slashes, for printing. */function shown(repo: string, path: string): string {@@ -1429,7 +1458,7 @@ function shown(repo: string, path: string): string {}/** `graft init`. */-async function runInitCommand(dir: string, opts: InitOptions): Promise<{ ids: string[] } | null> {+async function runInitCommand(dir: string, opts: InitOptions, progress?: InitProgress): Promise<{ ids: string[] } | null> {if (opts.listAgents) {for (const id of [...hostIds(), "claude"]) console.log(id);return null;@@ -1570,6 +1599,15 @@ async function runInitCommand(dir: string, opts: InitOptions): Promise<{ ids: st}}+ if (progress?.mapped) {+ const g = loadGraphCached(contextDirFor(repo, children.length ? undefined : program.opts<GlobalOpts>().dir));+ progress.mapped({+ nodes: g?.meta.nodeCount ?? 0,+ edges: g?.meta.edgeCount ?? 0,+ files: g ? g.nodes.filter((n) => n.kind === "file").length : 0,+ });+ }+if (!verbose) {// Warnings and removals in full, whatever else is folded.const removed = [...new Set(reports.flatMap((r) => r.retracted))];@@ -1610,8 +1648,12 @@ async function runInitCommand(dir: string, opts: InitOptions): Promise<{ ids: st? undefined: async (found: T[]) => picked && picked.filter((i) => i >= from && i < from + found.length).map((i) => found[i - from]!);const learned: Note[] = [];+ const learnedFrom: Array<{ note: Note; sessions?: number }> = [];+ let sessionsRead = 0;if (pastRead) {const { result, saved, kept, cancelled } = await finishPastRead(repo, pastRead, keepFrom<Finding>(0));+ sessionsRead = result.read ?? 0;+ saved.forEach((note, i) => learnedFrom.push({ note, sessions: kept[i]?.sessions.length }));const offered = result.findings.length;if (saved.length) {const n = saved.length;@@ -1649,13 +1691,17 @@ async function runInitCommand(dir: string, opts: InitOptions): Promise<{ ids: stconsole.error(`· couldn't read PR reviews this time; ${cmd("graft init")} again tries again`);}learned.push(...saved);+ for (const note of saved) learnedFrom.push({ note, sessions: 0 });}learnedNow = learned.length > 0;+ progress?.learned?.({ notes: learnedFrom, sessions: sessionsRead });if (learnedNow) {console.error("· Claude follows them from your next session");if (learned.some((s) => s.scope === "repo")) console.error(commitLines({}, teammatesOn(repo), "repo").uncommitted);}}+ // Nothing read this run (already read once, or not Claude Code): the page still gets its stage.+ if (!(TRAIL && (pastRead || reviewRead))) progress?.learned?.({ notes: [], sessions: 0 });if (TRAIL && !learnedNow) {const home = notesHome.get(repo);if (home) {@@ -1716,6 +1762,107 @@ async function runInitCommand(dir: string, opts: InitOptions): Promise<{ ids: streturn { ids };}+/**+ * `trail init --connect <CODE>`: the onboarding on app.trailhq.com. Claims the+ * one-time code (a wrong or spent one stops here, before anything is written),+ * saves the workspace token where `trail login` keeps it, then runs init as+ * usual while the page ticks off connected, mapped and learned. At the end,+ * one summary of the repo goes up (a lookup's tokens saved, the learnings'+ * titles, teammates' branches from git: never code, diffs or session text),+ * then `done`. Offline, init still sets the repo up and says how to connect.+ */+async function runConnectInit(dir: string, opts: InitOptions): Promise<void> {+ if (opts.listAgents || opts.dryRun) {+ if (opts.dryRun) console.error("· --dry-run: not connecting");+ await runInitCommand(dir, opts);+ return;+ }+ const repo = resolve(dir);+ const server = opts.server?.trim().replace(/\/+$/, "");+ if (server) {+ if (!/^https?:\/\//.test(server)) {+ console.error(`✗ --server takes a URL, like https://dev.trailhq.com`);+ process.exitCode = 1;+ return;+ }+ process.env.TRAIL_URL = server;+ }+ const base = trailUrl();+ const code = normalizeCode(opts.connect ?? "");+ if (!code) {+ console.error(`✗ "${opts.connect ?? ""}" isn't a Trail code · it looks like TRL-7F2A-K9QD, from ${base}/welcome/code`);+ process.exitCode = 1;+ return;+ }+ const ref = repoRef(repo);+ const machine = machineName();+ const got = await claimConnectCode(base, code, { machine, repo: ref });+ const cloud = "cloud" in got ? got.cloud : null;+ if ("cloud" in got) {+ const cloud = got.cloud;+ writeCloud(cloud);+ // A sign-in link out from before is moot now.+ clearPending();+ console.error(`✓ connected to workspace ${cloud.workspace.name}`);+ track("brain_signup_settled", { outcome: "linked", mode: "connect", duration_bucket: durationBucket(0) }, { repo });+ } else if (got.reason === "invalid") {+ console.error(`✗ ${got.error} · get a new code at ${base}/welcome/code`);+ process.exitCode = 1;+ return;+ } else {+ console.error(`· couldn't reach Trail (${got.error}) · setting up this repo anyway; run ${cmd("graft init")} --connect ${code} again to connect`);+ }+ const reporter = cloud ? new OnboardingReporter(cloud, ref, { machine }) : null;+ void reporter?.stage("connected");++ // What init learned this run, kept for the summary.+ const heard: { notes: Array<{ note: Note; sessions?: number }>; sessions: number } = { notes: [], sessions: 0 };+ const progress: InitProgress | undefined = reporter+ ? {+ mapped: (m) => void reporter.stage("mapped", m),+ learned: (l) => {+ Object.assign(heard, l);+ const team = learningsSummary(repo, l.notes);+ void reporter.stage("learned", { learnings: team.length, sessions: l.sessions || Math.max(0, ...team.map((t) => t.sessions)) });+ },+ }+ : undefined;+ // The page's command is pasted into a terminal, but an agent may run it for+ // them: with no terminal to pick in, wire the agents this machine has.+ const interactive = process.stdin.isTTY && process.stderr.isTTY;+ const res = await runInitCommand(dir, interactive ? opts : { ...opts, yes: true }, progress);+ if (!reporter || !cloud) return;+ if (!res) {+ await reporter.flush();+ return;+ }++ // What Trail found, for the page: route B, summaries only.+ const learnings = learningsSummary(repo, heard.notes);+ const sessions = heard.sessions || Math.max(0, ...learnings.map((l) => l.sessions));+ const tokens = tokensOnOneLookup(repo, { contextDir: program.opts<GlobalOpts>().dir });+ const teamNotes = listNotes(repo, { branches: false }).filter((n) => n.scope === "repo" && !n.ref);+ const teammates = teammatesFromGit(repo, { learnings: teamNotes });+ const sent = await reporter.summary({ tokens, ...(sessions ? { sessions } : {}), learnings, teammates });+ await reporter.stage("done");+ await reporter.flush();+ // Claude Code gets the workspace's brains through one user-level `trail` entry.+ const brainsEntry = res.ids.includes("claude") && opts.global !== false ? installBrainsServer(homedir()) : null;+ if (sent) {+ const parts = [+ tokens ? `one lookup saved ${tokens.pct}% of the tokens` : null,+ `${learnings.length} learning${learnings.length === 1 ? "" : "s"}`,+ `${teammates.length} teammate branch${teammates.length === 1 ? "" : "es"} on your files`,+ ].filter(Boolean);+ console.error(`✓ sent ${cloud.workspace.name} a summary: ${parts.join(", ")} · titles, counts and names only, no code`);+ console.error(`· see what Trail found: ${base}/welcome/code/found`);+ } else {+ console.error(`· couldn't send the summary to Trail this time; ${cmd("graft init")} --connect works again with a new code`);+ }+ if (brainsEntry?.action === "created" || brainsEntry?.action === "updated")+ console.error(`✓ Claude Code gets your workspace's brains in every project · restart it to pick them up`);+}+/** What one target's wiring did, for the compact summary to report. */interface WireReport {/** Hosts whose files were removed because they were not selected. */@@ -1942,6 +2089,7 @@ function logoutCommand(name = "logout"): Command {.action(() => {const cloud = readCloud();clearPending();+ removeBrainsServer(homedir());if (!clearCloud()) {console.error("· not connected to a workspace");return;@@ -2323,6 +2471,8 @@ function statusCommand(name = "status"): Command {}if (!cloud) {if (cloudEnabled()) row("workspace", "not connected · Claude offers a link once there are learnings to share");+ } else if (cloud.via === "connect") {+ row("workspace", `${cloud.workspace.name} · gets a summary of the repos you run ${cmd("graft init")} --connect in · ${cloud.workspace.url}`);} elserow("workspace",diff --git a/src/cloud/nudge.ts b/src/cloud/nudge.tsindex 5e25932a..4b746f2d 100644--- a/src/cloud/nudge.ts+++ b/src/cloud/nudge.ts@@ -148,6 +148,8 @@ export function cloudLines(repo: string, opts: NudgeOptions): string[] {writeState({ linked: undefined }, env);return connectedLines(st.linked, agent);}+ // Connected from the onboarding: only summaries go up, so there's no repo to add.+ if (cloud.via === "connect") return [];return addRepoLines(repo, cloud.workspace.name, cloud.repos, st, agent, env, now);}diff --git a/src/cloud/onboarding.ts b/src/cloud/onboarding.tsnew file mode 100644index 00000000..8c70fadf--- /dev/null+++ b/src/cloud/onboarding.ts@@ -0,0 +1,524 @@+/**+ * `trail init --connect <CODE>`: the onboarding on app.trailhq.com.+ *+ * A person signs up on the web, picks "Writing Code", and is shown two+ * commands: install trail, then `trail init --connect TRL-XXXX-XXXX`. The code+ * is one-time and short-lived; claiming it gives this machine a workspace+ * token, kept where `trail login` keeps one (`~/.trail/cloud.json`).+ *+ * While init runs, the page ticks off stages as this sends them: connected,+ * mapped, learned, done. Before `done`, one summary of the repo goes up, for+ * the "What Trail found" page:+ *+ * - tokens: one real lookup on the fresh code map, and what it saved+ * - learnings: titles, a short line of each and how many sessions said it+ * - teammates: other people's recently pushed branches that change the+ * files this person works on, from git+ *+ * Summaries only (the onboarding's "route B"): never code, diffs or session+ * text. Every call is bounded and never throws; offline, init carries on and+ * says nothing about it.+ */+import { execFileSync } from "node:child_process";+import { hostname } from "node:os";+import { formatAsk, ask } from "../ask/ask.js";+import { contextDirFor } from "../context/node-file.js";+import { loadGraphCached } from "../graph/load.js";+import { buildRepoMap } from "../graph/map.js";+import { refreshBranches, safeRef } from "../notes/branches.js";+import { cleanSubject } from "../notes/edit-overlap.js";+import { changedFiles, ownPath } from "../notes/git-facts.js";+import { repoName, repoPlace } from "../notes/home.js";+import { listNotes, sectionLead, type Note } from "../notes/notes.js";+import { isError, trailUrl, type ApiError, type Cloud } from "./workspace.js";++type Fetch = typeof fetch;++/* -------------------------------------------------------------------------- */+/* the code */+/* -------------------------------------------------------------------------- */++/**+ * The code as the page shows it, `TRL-7F2A-K9QD`, from however it was pasted:+ * any case, with or without the prefix and dashes. Null when it can't be one.+ */+export function normalizeCode(raw: string): string | null {+ const s = raw.trim().toUpperCase().replace(/[\s_]+/g, "-");+ const bare = s.replace(/^TRL-?/, "").replace(/-/g, "");+ if (!/^[A-Z0-9]{8}$/.test(bare)) return null;+ return `TRL-${bare.slice(0, 4)}-${bare.slice(4)}`;+}++/**+ * The repo as the workspace names it: `{name, remote_url}`, from which Trail+ * derives its key. No path on this machine, and never a credential from the+ * remote: the URL is rebuilt from the repo's key (`github.com/acme/retry` →+ * `https://github.com/acme/retry`), so a token in an https remote stays here.+ * A repo with no remote sends its name alone.+ */+export interface RepoRef {+ name: string;+ remote_url?: string;+}++export function repoRef(repo: string): RepoRef {+ const place = repoPlace(repo);+ if (place.key.startsWith("local/")) return { name: repoName(place.key, place.checkout) };+ // The name as the remote spells it (`go-retryablehttp`, `Graft`); the key is lower-cased.+ const origin = git(place.checkout, ["remote", "get-url", "origin"], 5000)?.trim() ?? "";+ const last = origin.replace(/\.git\/?$/i, "").split(/[/:]/).pop() ?? "";+ const name = /^[A-Za-z0-9._-]+$/.test(last) ? last : place.key.split("/").pop()!;+ return { name, remote_url: `https://${place.key}` };+}++/** What the page shows for the terminal: `Rushabh's MacBook Pro` on a Mac, else the host name. */+export function machineName(): string {+ if (process.platform === "darwin") {+ try {+ const name = execFileSync("scutil", ["--get", "ComputerName"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2000 }).trim();+ if (name) return name.slice(0, 80);+ } catch {+ /* the host name below */+ }+ }+ try {+ return hostname().replace(/\.(local|lan|home)$/i, "").slice(0, 80);+ } catch {+ return "";+ }+}++export type ConnectResult =+ | { cloud: Cloud }+ /** The code is wrong, used or expired: say so, and connect nothing. */+ | { error: string; reason: "invalid" }+ /** Trail didn't answer: set up locally and say how to connect later. */+ | { error: string; reason: "offline" };++interface ConnectBody {+ token?: string;+ workspace?: { id?: string; name?: string; slug?: string; url?: string; invite_url?: string };+ user?: { id?: string; name?: string; email?: string };+}++async function post<T>(+ url: string,+ body: unknown,+ opts: { token?: string; timeoutMs?: number; fetchImpl?: Fetch },+): Promise<{ status: number; body: T } | ApiError> {+ const f = opts.fetchImpl ?? fetch;+ try {+ const headers: Record<string, string> = { "content-type": "application/json", accept: "application/json" };+ if (opts.token) headers.authorization = `Bearer ${opts.token}`;+ const res = await f(url, { method: "POST", headers, body: JSON.stringify(body), signal: AbortSignal.timeout(opts.timeoutMs ?? 10_000) });+ const text = await res.text();+ let json: unknown = null;+ try {+ json = text ? JSON.parse(text) : null;+ } catch {+ /* not JSON */+ }+ if (!res.ok) {+ const msg = (json as { error?: unknown } | null)?.error;+ return { error: typeof msg === "string" ? msg : `Trail answered ${res.status}`, status: res.status };+ }+ return { status: res.status, body: json as T };+ } catch (err) {+ const timedOut = err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError");+ return { error: timedOut ? "Trail didn't answer in time" : "couldn't reach Trail" };+ }+}++/**+ * Claim the one-time code: `POST /api/public/cli/connect`. Gives back the+ * connection to save, with no repos picked: the full learnings sync stays off+ * for a machine connected this way, so only the summary below goes up.+ */+export async function claimConnectCode(+ base: string,+ code: string,+ req: { machine: string; repo: RepoRef },+ opts: { fetchImpl?: Fetch; now?: number } = {},+): Promise<ConnectResult> {+ const r = await post<ConnectBody>(`${base}/api/public/cli/connect`, { code, machine: req.machine, repo: req.repo }, { fetchImpl: opts.fetchImpl, timeoutMs: 15_000 });+ if (isError(r)) {+ if (r.status === undefined || r.status >= 500) return { error: r.error, reason: "offline" };+ if (r.status === 403) return { error: "the account that made this code is no longer in that workspace", reason: "invalid" };+ if (r.status === 429) return { error: "too many tries just now; wait a minute and run it again", reason: "invalid" };+ return { error: "that code was already used, has expired, or isn't right", reason: "invalid" };+ }+ const b = r.body;+ const ws = b?.workspace;+ if (!b?.token || !ws?.name) return { error: "Trail's answer had no workspace in it", reason: "offline" };+ const id = ws.id ?? ws.slug ?? ws.name;+ return {+ cloud: {+ url: base,+ token: b.token,+ user: { name: b.user?.name ?? "", email: b.user?.email ?? "" },+ workspace: {+ id,+ name: ws.name,+ // readCloud needs a slug to count the connection; the connect answer may not carry one.+ slug: ws.slug || id,+ url: ws.url || `${base}/`,+ invite_url: ws.invite_url || `${base}/`,+ },+ repos: [],+ linkedAt: opts.now ?? Date.now(),+ via: "connect",+ },+ };+}++/* -------------------------------------------------------------------------- */+/* the stages and the summary */+/* -------------------------------------------------------------------------- */++export type Stage = "connected" | "mapped" | "learned" | "done";++export interface TokensSummary {+ /** What was asked, in words the page can show: `how Do works`. */+ question: string;+ /** The symbol asked about. */+ symbol: string;+ /** Tokens saved, the pack, and reading the files whole: the `tokens saved ≈` line's numbers. */+ saved: number;+ pack: number;+ baseline: number;+ pct: number;+ /** How many files the baseline reads whole. */+ files: number;+}++export interface LearningSummary {+ title: string;+ /** One line of it, no code blocks, at most 200 characters. */+ body: string;+ /** Past sessions it was said in; 0 when it didn't come from sessions. */+ sessions: number;+}++export interface TeammateSummary {+ name: string;+ email: string;+ /** `kumar/retry`, without `origin/`. */+ branch: string;+ /** The files it changes that this person works on too (or, with no history of theirs, the repo's busiest). */+ files: string[];+ /** One line, from the branch's commit subjects. */+ change: string;+ /** When its newest commit was made, ISO. */+ pushed_at: string;+ /** Commits on the branch since it left the default branch. */+ commits?: number;+ /** When it changes a file one of this repo's learnings is about: which, and which learning. */+ conflict?: string;+}++export interface RepoSummary {+ repo: RepoRef;+ tokens: TokensSummary | null;+ /** Past sessions init read for learnings; absent when it read none this time. */+ sessions?: number;+ learnings: LearningSummary[];+ teammates: TeammateSummary[];+}++/**+ * Sends the stages and the summary for one `init --connect`, in order. The+ * first call that can't reach Trail turns the rest off, so a laptop offline+ * waits on one timeout at most. Never throws.+ */+export class OnboardingReporter {+ private offline = false;+ private chain: Promise<unknown> = Promise.resolve();+ readonly sent: Array<{ path: string; body: unknown; ok: boolean }> = [];++ constructor(+ private readonly cloud: Cloud,+ readonly repo: RepoRef,+ private readonly opts: { fetchImpl?: Fetch; timeoutMs?: number; machine?: string } = {},+ ) {}++ private send(path: string, body: unknown): Promise<boolean> {+ const next = this.chain.then(async () => {+ if (this.offline) return false;+ const r = await post(`${this.cloud.url}${path}`, body, { token: this.cloud.token, fetchImpl: this.opts.fetchImpl, timeoutMs: this.opts.timeoutMs ?? 5_000 });+ const ok = !isError(r);+ // No answer at all: offline, or Trail is down. An HTTP error is this call's alone.+ if (isError(r) && r.status === undefined) this.offline = true;+ this.sent.push({ path, body, ok });+ return ok;+ });+ this.chain = next.catch(() => false);+ return next.catch(() => false);+ }++ /** One stage, for the page to tick off. */+ stage(stage: Stage, data: Record<string, unknown> = {}): Promise<boolean> {+ return this.send("/api/cli/onboarding/events", { repo: this.repo, stage, machine: this.opts.machine, data });+ }++ summary(s: Omit<RepoSummary, "repo">): Promise<boolean> {+ return this.send("/api/cli/repos/summary", { repo: this.repo, ...s });+ }++ /** Wait for everything sent so far. */+ async flush(): Promise<void> {+ await this.chain;+ }+}++/* tokens ------------------------------------------------------------------- */++/** The numbers in `ask`'s `[trail] tokens saved ≈ N (P%) — this pack ≈ … tok vs reading the F source file(s) whole ≈ B tok` line. */+export function parseAskSavings(text: string): Omit<TokensSummary, "question" | "symbol"> | null {+ const m = text.match(/\[(?:graft|trail)\] tokens saved ≈ ([\d,]+) \((\d+)%\) — this pack ≈ ([\d,]+) tok vs reading the (\d+) source file\(s\) whole ≈ ([\d,]+) tok/);+ if (!m) return null;+ const n = (s: string) => Number(s.replace(/,/g, ""));+ return { saved: n(m[1]!), pct: n(m[2]!), pack: n(m[3]!), files: n(m[4]!), baseline: n(m[5]!) };+}++/**+ * One real lookup on the code map, as an agent would make it: a question+ * about the repo's most central symbol (most incoming edges), answered with+ * the code inlined, and what that saved against reading the files it covers+ * whole. The next most central is tried when a lookup saves nothing (tiny+ * files). Null without a graph.+ */+export function tokensOnOneLookup(repo: string, opts: { contextDir?: string; tries?: number } = {}): TokensSummary | null {+ try {+ const graph = loadGraphCached(contextDirFor(repo, opts.contextDir));+ if (!graph) return null;+ const hubs = buildRepoMap(graph, { hotspots: Math.max(1, opts.tries ?? 5) }).hotspots;+ for (const hub of hubs) {+ const query = `how does ${hub.name} work`;+ const r = ask(repo, query, { source: true, limit: 5, contextDir: opts.contextDir });+ const got = parseAskSavings(formatAsk(r));+ if (got && got.saved > 0) return { question: `how ${hub.name} works`, symbol: hub.name, ...got };+ }+ return null;+ } catch {+ return null;+ }+}++/* learnings ---------------------------------------------------------------- */++/** How many sessions a learning read from past sessions was said in, from the line init writes under it. */+export function sessionsIn(body: string): number {+ const m = body.match(/Told to Claude in (\d+) past sessions/);+ return m ? Number(m[1]) : 0;+}++/**+ * One line of a learning, for a card: the first point under `## Decided` (or+ * the first line of prose), no code blocks, headings or provenance line, at+ * most 200 characters.+ */+export function shortBody(body: string): string {+ const prose = body+ .replace(/```[\s\S]*?(```|$)/g, " ")+ .split(/\r?\n/)+ .filter((l) => !/^_(Told to Claude|Flagged in review) /.test(l.trim()));+ const text = prose.join("\n");+ const lead =+ sectionLead(text, "Decided") ??+ sectionLead(text, "Watch out") ??+ prose.map((l) => l.trim()).find((l) => l && !l.startsWith("#")) ??+ "";+ const one = lead.replace(/^[-*]\s+/, "").replace(/\s+/g, " ").trim();+ return one.length > 200 ? `${one.slice(0, 199)}…` : one;+}++/**+ * The team's learnings in this repo, for the summary: what init just learned+ * when it learned something (with the sessions each was said in), else what+ * `.trail/learnings/` already has. Never a personal one: those stay on this+ * machine.+ */+export function learningsSummary(repo: string, learned: Array<{ note: Note; sessions?: number }> | null, max = 10): LearningSummary[] {+ try {+ const notes: Array<{ note: Note; sessions?: number }> = learned?.length+ ? learned.filter((l) => l.note.scope !== "personal")+ : listNotes(repo, { branches: false })+ .filter((n) => n.scope === "repo" && !n.ref)+ .map((note) => ({ note }));+ return notes.slice(0, max).map(({ note, sessions }) => ({+ title: note.title.slice(0, 200),+ body: shortBody(note.body),+ sessions: sessions ?? sessionsIn(note.body),+ }));+ } catch {+ return [];+ }+}++/* teammates ---------------------------------------------------------------- */++function git(repo: string, args: string[], timeout = 15_000): string | null {+ try {+ return execFileSync("git", args, {+ cwd: repo,+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],+ timeout,+ maxBuffer: 16 * 1024 * 1024,+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },+ });+ } catch {+ return null;+ }+}++const BOT = /\[bot\]|^(dependabot|github-actions|renovate)\b/i;++/** Files `email` changed in the last `days` days on any branch, plus what's uncommitted here. */+export function myRecentFiles(repo: string, email: string, days = 30): string[] {+ const out = new Set<string>(changedFiles(repo, undefined, 200));+ if (email) {+ const pattern = `<${email.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}>`;+ const log = git(repo, ["log", "--all", "--no-merges", `--since=${days}.days`, `--author=${pattern}`, "--name-only", "--format="]);+ for (const f of (log ?? "").split("\n")) if (f.trim() && !ownPath(f.trim())) out.add(f.trim());+ }+ return [...out].slice(0, 500);+}++/** The repo's busiest files lately: the stand-in for "files you work on" when you have no history here. */+export function hottestFiles(repo: string, n = 30): string[] {+ const count = new Map<string, number>();+ const log = git(repo, ["log", "--no-merges", "--since=90.days", "-n", "2000", "--name-only", "--format="]) || git(repo, ["log", "--no-merges", "-n", "300", "--name-only", "--format="]);+ for (const raw of (log ?? "").split("\n")) {+ const f = raw.trim();+ if (f && !ownPath(f)) count.set(f, (count.get(f) ?? 0) + 1);+ }+ return [...count].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, n).map(([f]) => f);+}++/** One line of what a branch does, from its commit subjects, newest first. */+function changeLine(repo: string, base: string, ref: string): string {+ const subjects = (git(repo, ["log", "--no-merges", "--format=%s", "-n", "5", `${base}..${ref}`]) ?? "")+ .split("\n")+ .map((s) => cleanSubject(s))+ .filter(Boolean);+ const line = [...new Set(subjects)].slice(0, 3).join("; ");+ return line.length > 160 ? `${line.slice(0, 159)}…` : line;+}++/**+ * `git fetch` in the foreground, at the end of init, without ever stopping to+ * ask: no credential prompt, and no ssh passphrase prompt unless the person+ * set up their own ssh command (then theirs is used as is).+ */+function fetchQuietly(repo: string): void {+ try {+ const env: NodeJS.ProcessEnv = { ...process.env, GIT_TERMINAL_PROMPT: "0" };+ if (!env.GIT_SSH_COMMAND && !git(repo, ["config", "core.sshCommand"])?.trim()) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";+ execFileSync("git", ["fetch", "--quiet", "--prune", "origin"], { cwd: repo, stdio: "ignore", timeout: 20_000, env });+ } catch {+ /* offline, or no origin: the refs already here */+ }+}++/**+ * The names a learning is about, to look for in a teammate's change: the+ * symbols its `touches` name (`client.go#Do`), and code-like words in its+ * title and lead line (`defaultRetryMax`, `retry_max`, `Do()`). Plain words+ * are left out: "retry" in a learning says nothing about a change.+ */+export function learningTerms(n: Note): string[] {+ const terms = new Set<string>();+ for (const t of n.touches) {+ const sym = t.split("#")[1];+ if (sym) terms.add(sym.split(".").pop()!);+ }+ const text = `${n.title} ${shortBody(n.body)}`;+ // camelCase, PascalCase with an inner capital, snake_case, or a call: `Do()`.+ for (const w of text.match(/\b[A-Za-z_][A-Za-z0-9_]*\b(\(\))?/g) ?? []) {+ const word = w.replace(/\(\)$/, "");+ if (w.endsWith("()") || /[a-z][A-Z]/.test(word) || /[A-Za-z]_[A-Za-z]/.test(word)) terms.add(word);+ }+ return [...terms].filter((t) => t.length >= 2);+}++/**+ * When a teammate's branch changes a name one of the team's learnings is+ * about, in a file that learning touches: `Changes defaultRetryMax in+ * client.go, which your learning "Keep defaultRetryMax at 4" is about.` Read+ * from the branch's diff here; only this line goes up. Nothing when the+ * learning names nothing code-like, or the change doesn't touch it.+ */+export function conflictLine(repo: string, base: string, ref: string, files: string[], learnings: Note[]): string | undefined {+ const changed = new Set(files);+ for (const n of learnings) {+ if (n.scope === "personal") continue;+ const terms = learningTerms(n);+ if (terms.length === 0) continue;+ for (const file of n.touches.map((t) => t.split("#")[0]!).filter((f) => changed.has(f))) {+ const diff = git(repo, ["diff", "--unified=0", `${base}...${ref}`, "--", file]) ?? "";+ const lines = diff.split("\n").filter((l) => /^[+-]/.test(l) && !/^(\+\+\+|---) /.test(l));+ const hit = terms.find((t) => lines.some((l) => new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`).test(l)));+ if (hit) {+ const line = `Changes ${hit} in ${file}, which your learning "${n.title.replace(/"/g, "'")}" is about.`;+ return line.length > 300 ? `${line.slice(0, 299)}…` : line;+ }+ }+ }+ return undefined;+}++/**+ * Teammates' work in the same place: remote branches whose newest commit is+ * from the last `days` days and from someone other than this person, that+ * change files this person changed lately (or the repo's busiest files, when+ * they have no history here). Newest first. Fetches first unless+ * `fetch: false` (or TRAIL_NO_FETCH). Names, emails, branch and file names and+ * commit subjects only: never a diff.+ */+export function teammatesFromGit(+ repo: string,+ opts: { days?: number; now?: number; fetch?: boolean; max?: number; learnings?: Note[] } = {},+): TeammateSummary[] {+ try {+ const now = opts.now ?? Date.now();+ const days = opts.days ?? 14;+ const me = (git(repo, ["config", "user.email"]) ?? "").trim().toLowerCase();+ const myName = (git(repo, ["config", "user.name"]) ?? "").trim().toLowerCase();+ if (opts.fetch !== false && !process.env.TRAIL_NO_FETCH) fetchQuietly(repo);+ const cache = refreshBranches(repo, { fetch: false, now });+ if (!cache.base) return [];+ const mine = new Set(myRecentFiles(repo, me));+ const where = mine.size ? mine : new Set(hottestFiles(repo));+ const out: TeammateSummary[] = [];+ for (const b of cache.branches) {+ if (now - b.at > days * 24 * 60 * 60 * 1000) continue;+ const [name = "", email = ""] = (git(repo, ["log", "-1", "--format=%aN%x09%aE", b.ref]) ?? "").trim().split("\t");+ if (!name || BOT.test(name)) continue;+ if ((me && email.toLowerCase() === me) || (myName && name.toLowerCase() === myName)) continue;+ const files = b.files.filter((f) => !ownPath(f) && where.has(f));+ if (files.length === 0) continue;+ const commits = Number((git(repo, ["rev-list", "--count", `${cache.base}..${b.ref}`]) ?? "").trim());+ const conflict = conflictLine(repo, cache.base, b.ref, files, opts.learnings ?? []);+ out.push({+ name: name.slice(0, 80),+ email: email.slice(0, 120),+ branch: safeRef(b.ref.replace(/^origin\//, "")),+ files: files.slice(0, 20),+ change: changeLine(repo, cache.base, b.ref),+ pushed_at: new Date(b.at).toISOString(),+ ...(Number.isFinite(commits) && commits > 0 ? { commits } : {}),+ ...(conflict ? { conflict } : {}),+ });+ if (out.length >= (opts.max ?? 10)) break;+ }+ return out.sort((a, b) => b.pushed_at.localeCompare(a.pushed_at));+ } catch {+ return [];+ }+}++/** The Trail a code is claimed against: `--server`, TRAIL_URL, or Trail cloud. */+export function connectBase(env: NodeJS.ProcessEnv = process.env): string {+ return trailUrl(env);+}diff --git a/src/cloud/workspace-sync.ts b/src/cloud/workspace-sync.tsindex d1a0d4aa..23228f1b 100644--- a/src/cloud/workspace-sync.ts+++ b/src/cloud/workspace-sync.ts@@ -89,9 +89,14 @@ function statePath(repo: string): string {return join(cacheDir(repo), "trail-workspace-sync.json");}-/** Whether the repo at `checkout` is one of the workspace's. */+/**+ * Whether the repo at `checkout` is one of the workspace's, so its learnings+ * and uses go up. Never on a machine connected by `trail init --connect`: that+ * one sends a repo summary only (titles and counts, no learning bodies, no+ * searches), whatever repos the workspace lists.+ */export function inWorkspace(checkout: string, cloud: Cloud | null = readCloud()): boolean {- return !!cloud && cloud.repos.includes(repoPlace(checkout).key);+ return !!cloud && cloud.via !== "connect" && cloud.repos.includes(repoPlace(checkout).key);}/**@@ -149,7 +154,7 @@ function sendable(e: ActivityEvent, cloud: Cloud): boolean {* connected, or another repo, and nothing is written. Never throws.*/export function recordActivity(e: ActivityEvent, cloud: Cloud | null = readCloud()): void {- if (!cloud || !cloud.repos.includes(e.repo)) return;+ if (!cloud || cloud.via === "connect" || !cloud.repos.includes(e.repo)) return;try {const p = outboxPath();appendFileSync(p, `${JSON.stringify(e)}\n`);diff --git a/src/cloud/workspace.ts b/src/cloud/workspace.tsindex 97e5c466..5348695a 100644--- a/src/cloud/workspace.ts+++ b/src/cloud/workspace.ts@@ -42,6 +42,12 @@ export interface Cloud {/** Repo keys in the workspace (`github.com/owner/name`), as of the last look. */repos: string[];linkedAt: number;+ /**+ * `connect`: connected by `trail init --connect <code>` from the onboarding+ * on the web. Such a machine sends a repo summary (titles, counts, names)+ * and never the full learnings sync, so it's never asked to add repos.+ */+ via?: "connect";}function cloudPath(env: NodeJS.ProcessEnv = process.env): string {diff --git a/src/hosts/claude-global.ts b/src/hosts/claude-global.tsindex c773a0ba..385ace43 100644--- a/src/hosts/claude-global.ts+++ b/src/hosts/claude-global.ts@@ -122,7 +122,8 @@ export function installClaudeGlobal(home: string, brand: Brand = 'graft'): Globa// graft's keeps serving every repo still wired as graft; a trail repo turns// it off for its own folder (see disableGraftServerIn).if (brand === 'trail') {- out.push(dropUserServer(mcp.id, mcp.path, 'trail'));+ // The workspace-brains server `init --connect` adds stays: it serves no repo tools.+ out.push(dropUserServer(mcp.id, mcp.path, 'trail', isBrainsServer));return out;}try {@@ -134,13 +135,14 @@ export function installClaudeGlobal(home: string, brand: Brand = 'graft'): Globareturn out;}-/** Remove one user-scope server from `~/.claude.json`, leaving everything else. */-function dropUserServer(id: string, path: string, name: string): GlobalWrite {+/** Remove one user-scope server from `~/.claude.json`, leaving everything else; `keep` spares an entry it accepts. */+function dropUserServer(id: string, path: string, name: string, keep?: (entry: unknown) => boolean): GlobalWrite {try {const loaded = readJsonObject(path);if (loaded === 'unparseable') return { id, path, action: 'skipped-unparseable' };const servers = loaded.root.mcpServers;if (!servers || typeof servers !== 'object' || !(name in servers)) return { id, path, action: 'unchanged' };+ if (keep?.(servers[name])) return { id, path, action: 'unchanged' };delete servers[name];writeFileSync(path, `${JSON.stringify(loaded.root, null, 2)}\n`);return { id, path, action: 'updated' };@@ -215,3 +217,39 @@ export function fitTrailServerToMachine(home: string, folder: string, has: { trareturn { id, path, action: 'skipped-unparseable' };}}++/* -------------------------------------------------------------------------- */+/* the workspace's brains, for Claude Code */+/* -------------------------------------------------------------------------- */++/** The flag that makes `trail mcp` serve only the workspace's brain tools. */+export const BRAINS_FLAG = '--brains';++/** Whether a user-scope `trail` entry is the brains-only server (`trail mcp --brains`). */+export function isBrainsServer(entry: unknown): boolean {+ const args = (entry as { args?: unknown } | null)?.args;+ return Array.isArray(args) && args.includes(BRAINS_FLAG);+}++/**+ * Once this machine is connected to a Trail workspace, Claude Code gets one+ * `trail` entry at the user MCP scope (`~/.claude.json`, every project): a+ * server that serves only the workspace's brain tools. trail gives Claude+ * Code no repo-tools server (its hooks and the `trail` command do that work),+ * so this one lists the four brain tools and nothing else. Best-effort.+ */+export function installBrainsServer(home: string): GlobalWrite {+ const id = 'claude-global-brains';+ const path = join(home, '.claude.json');+ try {+ const { command, args } = serverEntry({ brand: 'trail' });+ return mergeJsonKey(id, path, 'mcpServers', { command, args: [...args, BRAINS_FLAG] }, 'trail');+ } catch {+ return { id, path, action: 'skipped-unparseable' };+ }+}++/** Take the brains server out again (`trail logout`). Leaves any other `trail` entry alone. */+export function removeBrainsServer(home: string): GlobalWrite {+ return dropUserServer('claude-global-brains', join(home, '.claude.json'), 'trail', (e) => !isBrainsServer(e));+}diff --git a/src/mcp/brains.ts b/src/mcp/brains.tsnew file mode 100644index 00000000..514941d7--- /dev/null+++ b/src/mcp/brains.ts@@ -0,0 +1,236 @@+/**+ * The workspace's brains, served by the local trail MCP server.+ *+ * Once this machine is connected to a Trail workspace (`trail init --connect`,+ * or `trail login`), the one `trail` MCP entry Claude Code already has also+ * answers the workspace connector's brain tools: `list_brains`,+ * `get_context`, `search_rules` and `get_rules`. Each call is passed to the+ * workspace connector (`<trail>/api/v1/mcp`, MCP over streamable HTTP) with+ * the stored token, and its answer comes back as is: every result names the+ * brain and the rule it came from.+ *+ * The repo tools never wait on this. Not connected, the brain tools aren't+ * listed; connected but offline, they're listed and answer with a soft error,+ * while the repo tools keep working.+ */+import type { ToolDef } from './tools.js';+import { readCloud, type Cloud } from '../cloud/workspace.js';++/** The workspace connector's brain tools, the only ones passed through. */+export const BRAIN_TOOLS = ['list_brains', 'get_context', 'search_rules', 'get_rules'] as const;++export function isBrainTool(name: string): boolean {+ return (BRAIN_TOOLS as readonly string[]).includes(name);+}++/**+ * What's listed when the connector can't be asked for its own list (offline,+ * slow): the same four tools, as the workspace connector describes them.+ */+export const BRAIN_TOOL_DEFS: ToolDef[] = [+ {+ name: 'list_brains',+ description:+ "Your Trail workspace's brains (team knowledge: brand, product, conventions, decisions), with how many rules each has. Use it to pick a brain for get_rules.",+ inputSchema: { type: 'object', properties: {} },+ },+ {+ name: 'get_context',+ description:+ "The rules from your Trail workspace's brains that apply to a task, each naming its brain and rule. Ask before writing anything that has to follow the team's brand, product or conventions.",+ inputSchema: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'the task or question, in a short phrase' },+ brain: { type: 'string', description: "optional: one brain's name, slug or id; leave out to search every brain" },+ },+ required: ['query'],+ },+ },+ {+ name: 'search_rules',+ description: "Search the rules in your Trail workspace's brains by meaning. Each result names its brain and rule.",+ inputSchema: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'what to look for' },+ brain: { type: 'string', description: "optional: one brain's name, slug or id; leave out to search every brain" },+ },+ required: ['query'],+ },+ },+ {+ name: 'get_rules',+ description: "Every rule in one of your Trail workspace's brains.",+ inputSchema: {+ type: 'object',+ properties: { brain: { type: 'string', description: "the brain's name, slug or id, as list_brains shows it" } },+ required: ['brain'],+ },+ },+];++/** The workspace connector for a connection: TRAIL_MCP_URL, else `<trail>/api/v1/mcp`. */+export function connectorUrl(cloud: Cloud, env: NodeJS.ProcessEnv = process.env): string {+ return (env.TRAIL_MCP_URL || `${cloud.url.replace(/\/+$/, '')}/api/v1/mcp`).replace(/\/+$/, '');+}++export interface CallResult {+ content: Array<{ type: string; text?: string; [k: string]: unknown }>;+ isError?: boolean;+ structuredContent?: unknown;+}++type Fetch = typeof fetch;++/** The JSON-RPC message answering `id`, from a JSON body or an SSE stream. */+function pickReply(contentType: string, text: string, id: number): any {+ if (contentType.includes('text/event-stream')) {+ for (const line of text.split(/\r?\n/)) {+ if (!line.startsWith('data:')) continue;+ try {+ const msg = JSON.parse(line.slice(5).trim());+ if (msg && msg.id === id) return msg;+ } catch {+ /* a partial event */+ }+ }+ return null;+ }+ try {+ const msg = JSON.parse(text);+ if (Array.isArray(msg)) return msg.find((m) => m?.id === id) ?? null;+ return msg;+ } catch {+ return null;+ }+}++/**+ * A small MCP client for the workspace connector. One per server process:+ * it initializes once, keeps a session id if the connector hands one out+ * (it runs stateless today, so it usually doesn't), and reads the connection+ * from `~/.trail/cloud.json` on every call, so `trail logout` or a new+ * `--connect` takes effect without restarting the agent.+ */+export class BrainProxy {+ private nextId = 1;+ private session: { token: string; id?: string; protocol: string } | null = null;+ private listing: Promise<ToolDef[]> | null = null;++ constructor(+ private readonly opts: { env?: NodeJS.ProcessEnv; fetchImpl?: Fetch; timeoutMs?: number; version?: string } = {},+ ) {}++ private cloud(): Cloud | null {+ return readCloud(this.opts.env);+ }++ /** Whether this machine is connected to a workspace, so the brain tools are offered. */+ connected(): boolean {+ return this.cloud() !== null;+ }++ private async rpc(cloud: Cloud, method: string, params: object | undefined, notify = false): Promise<any> {+ const f = this.opts.fetchImpl ?? fetch;+ const id = this.nextId++;+ const headers: Record<string, string> = {+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ authorization: `Bearer ${cloud.token}`,+ };+ if (this.session?.id) headers['mcp-session-id'] = this.session.id;+ if (this.session) headers['mcp-protocol-version'] = this.session.protocol;+ const body = notify ? { jsonrpc: '2.0', method, params } : { jsonrpc: '2.0', id, method, params };+ const res = await f(connectorUrl(cloud, this.opts.env), {+ method: 'POST',+ headers,+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(this.opts.timeoutMs ?? 15_000),+ });+ const text = await res.text();+ if (notify) return null;+ if (res.status === 401 || res.status === 403) throw new Error('your Trail workspace token was not accepted; run `trail init --connect <code>` with a new code from app.trailhq.com');+ if (!res.ok) throw new Error(`the Trail workspace answered ${res.status}`);+ const sid = res.headers.get('mcp-session-id');+ if (sid && this.session) this.session.id = sid;+ const msg = pickReply(res.headers.get('content-type') ?? '', text, id);+ if (!msg) throw new Error('the Trail workspace sent an answer trail could not read');+ if (msg.error) throw new Error(msg.error.message ?? 'the Trail workspace returned an error');+ return msg.result;+ }++ /** Initialize once per token: a new connection starts a new session. */+ private async ready(cloud: Cloud): Promise<void> {+ if (this.session?.token === cloud.token) return;+ this.session = null;+ const f = this.opts.fetchImpl ?? fetch;+ const id = this.nextId++;+ const res = await f(connectorUrl(cloud, this.opts.env), {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ authorization: `Bearer ${cloud.token}`,+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id,+ method: 'initialize',+ params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'trail', version: this.opts.version ?? '0' } },+ }),+ signal: AbortSignal.timeout(this.opts.timeoutMs ?? 15_000),+ });+ const text = await res.text();+ if (res.status === 401 || res.status === 403) throw new Error('your Trail workspace token was not accepted; run `trail init --connect <code>` with a new code from app.trailhq.com');+ if (!res.ok) throw new Error(`the Trail workspace answered ${res.status}`);+ const msg = pickReply(res.headers.get('content-type') ?? '', text, id);+ const protocol = typeof msg?.result?.protocolVersion === 'string' ? msg.result.protocolVersion : '2025-06-18';+ this.session = { token: cloud.token, id: res.headers.get('mcp-session-id') ?? undefined, protocol };+ await this.rpc(cloud, 'notifications/initialized', undefined, true).catch(() => {});+ }++ /**+ * The brain tools to list: the connector's own definitions of the four+ * when it answers in time, else the built-in ones. Empty when not connected.+ * Asked once per process; the answer is reused.+ */+ listTools(): Promise<ToolDef[]> {+ const cloud = this.cloud();+ if (!cloud) return Promise.resolve([]);+ this.listing ??= (async () => {+ try {+ await this.ready(cloud);+ const result = await this.rpc(cloud, 'tools/list', {});+ const remote = (Array.isArray(result?.tools) ? result.tools : []) as ToolDef[];+ const brains = remote.filter((t) => t && isBrainTool(t.name));+ if (brains.length === 0) return BRAIN_TOOL_DEFS;+ return brains.map((t) => ({ name: t.name, description: t.description ?? '', inputSchema: t.inputSchema ?? { type: 'object' } }));+ } catch {+ return BRAIN_TOOL_DEFS;+ }+ })();+ return this.listing;+ }++ /** Pass one brain tool call to the workspace. Never throws: a failure is a soft error the agent can read. */+ async callTool(name: string, args: Record<string, unknown>): Promise<CallResult> {+ const cloud = this.cloud();+ if (!cloud) {+ return { content: [{ type: 'text', text: 'not connected to a Trail workspace · run `trail init --connect <code>` with the code from app.trailhq.com' }], isError: true };+ }+ try {+ await this.ready(cloud);+ const result = await this.rpc(cloud, 'tools/call', { name, arguments: args });+ const content = Array.isArray(result?.content) ? result.content : [{ type: 'text', text: JSON.stringify(result ?? null) }];+ const out: CallResult = { content, isError: result?.isError === true };+ if (result?.structuredContent !== undefined) out.structuredContent = result.structuredContent;+ return out;+ } catch (err) {+ // A dropped session is worth one fresh start.+ this.session = null;+ const why = err instanceof Error && err.name !== 'TimeoutError' && err.name !== 'AbortError' && !/fetch failed/.test(err.message) ? err.message : "couldn't reach your Trail workspace";+ return { content: [{ type: 'text', text: `${why} · the repo tools still work` }], isError: true };+ }+ }+}diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 3ae6ebbe..0e5ec59b 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -12,6 +12,7 @@ import { runningVersion } from '../upkeep.js';import { maybeFlushInBackground, track } from '../telemetry/index.js';import { brand, inBrand } from '../brand.js';import { canonicalToolName } from './tool-names.js';+import { BRAIN_TOOL_DEFS, BrainProxy, isBrainTool } from './brains.js';/*** MCP tool name → the command enum the telemetry contract knows. A tool absent@@ -28,6 +29,16 @@ const TOOL_COMMAND: Record<string, string> = {graft_check_freshness: 'check',};+/** How long `tools/list` waits on the workspace for its brain tools before listing the built-in ones. */+const BRAIN_LIST_WAIT_MS = 4000;++/** Said in `instructions` when this machine is connected to a Trail workspace. */+const BRAINS_LINE =+ "Connected to a Trail workspace: list_brains, get_context, search_rules and get_rules answer from the team's brains (brand, product, conventions, decisions); each result names its brain and rule. Use them for how the team does things, the tools above for the code.";++/** What the brains-only server says when this machine isn't connected (any more). */+const NOT_CONNECTED_LINE = 'Not connected to a Trail workspace: run `trail init --connect <code>` with the code from app.trailhq.com to use its brains here.';+function send(msg: object): void {process.stdout.write(`${JSON.stringify(msg)}\n`);}@@ -70,14 +81,18 @@ function advertised(root: string, dirOverride?: string): typeof TOOLS {* resolves package.json relative to the calling module, and from `dist/mcp/` that* lookup misses. The caller already knows it.*/-export function startMcpServer(root: string, dirOverride?: string, version = '0'): void {+export function startMcpServer(root: string, dirOverride?: string, version = '0', opts: { brainsOnly?: boolean } = {}): void {+ // `trail mcp --brains`: the one entry Claude Code gets once connected to a+ // workspace. It serves the workspace's brain tools and nothing of the repo's,+ // so it does none of the repo upkeep either: it starts in every project.+ const brainsOnly = opts.brainsOnly === true;// The self-maintenance pass, run once at boot. This is the ONLY channel that// reaches hosts with no hook support (Cursor, and any plain MCP client): it// refreshes rule files an older `graft init` wrote, and kicks off the cached// registry check. Both are fail-soft, and the resulting lines ride along in// `instructions` below — stdout is protocol-only, so there is nowhere else to// put them. Never blocks: the registry fetch happens in a detached child.- const upkeep = runUpkeep(root, runningVersion()).lines;+ const upkeep = brainsOnly ? [] : runUpkeep(root, runningVersion()).lines;for (const line of upkeep) console.error(line);// Same deal for the telemetry queue: flushed from a detached child at boot, so// a Cursor user who never touches the CLI still gets their events out.@@ -86,7 +101,12 @@ export function startMcpServer(root: string, dirOverride?: string, version = '0'// log nobody reads, so printing it here would mark the disclosure as shown// without anyone having seen it. It stays pending for the next CLI command,// and `graft init`'s picker is the channel that reached this user already.- maybeFlushInBackground();+ if (!brainsOnly) maybeFlushInBackground();++ // The workspace's brains, when this machine is connected to one: asked for+ // their list now, so it's in hand by the time the client lists tools.+ const brains = new BrainProxy({ version });+ if (brains.connected()) void brains.listTools();const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });rl.on('line', (line) => {@@ -108,7 +128,9 @@ export function startMcpServer(root: string, dirOverride?: string, version = '0'capabilities: { tools: {} },serverInfo: { name: brand(), version },// The one channel that survives tool deferral — see ./instructions.ts.- instructions: upkeep.length ? `${upkeep.join('\n')}\n\n${mcpInstructions()}` : mcpInstructions(),+ instructions: [upkeep.length ? upkeep.join('\n') : '', brainsOnly ? '' : mcpInstructions(), brains.connected() ? BRAINS_LINE : brainsOnly ? NOT_CONNECTED_LINE : '']+ .filter(Boolean)+ .join('\n\n'),});return;case 'notifications/initialized':@@ -120,13 +142,32 @@ export function startMcpServer(root: string, dirOverride?: string, version = '0'case 'tools/list': {if (isNotification) return;// Under trail, the same tools as `trail_*`, described in trail's words.- reply(id, { tools: advertised(root, dirOverride).map((t) => ({ name: inBrand(t.name), description: inBrand(t.description), inputSchema: t.inputSchema })) });+ const local = (brainsOnly ? [] : advertised(root, dirOverride)).map((t) => ({ name: inBrand(t.name), description: inBrand(t.description), inputSchema: t.inputSchema }));+ if (!brains.connected()) {+ reply(id, { tools: local });+ return;+ }+ // Connected: the workspace's brain tools too. A slow workspace never holds the repo tools up for long.+ const capped = new Promise<typeof BRAIN_TOOL_DEFS>((r) => setTimeout(() => r(BRAIN_TOOL_DEFS), BRAIN_LIST_WAIT_MS).unref());+ Promise.race([brains.listTools(), capped]).then(+ (remote) => reply(id, { tools: [...local, ...remote] }),+ () => reply(id, { tools: local }),+ );return;}case 'tools/call': {if (isNotification) return;const name = String(params?.name ?? '');const args = (params?.arguments ?? {}) as Record<string, unknown>;+ if (isBrainTool(name)) {+ // A workspace brain: passed to the workspace as is. Never throws.+ brains.callTool(name, args).then((r) => reply(id, r));+ return;+ }+ if (brainsOnly) {+ reply(id, { content: [{ type: 'text', text: `this server answers the workspace's brain tools only; ${name} isn't one` }], isError: true });+ return;+ }// Async because a tool call may rebuild the graph first (see// graph/refresh.ts). `callTool` absorbs its own errors, so the only thing// that can reject here is a bug — surface it as a JSON-RPC error ratherdiff --git a/test/fake-trail-server.ts b/test/fake-trail-server.tsnew file mode 100644index 00000000..6ccb1552--- /dev/null+++ b/test/fake-trail-server.ts@@ -0,0 +1,129 @@+/**+ * A stand-in for app.trailhq.com's CLI routes, over real HTTP, for the+ * `init --connect` and MCP proxy tests (and for trying the flow by hand:+ * `node --import tsx test/fake-trail-server.ts 8787`, then+ * `TRAIL_URL=http://127.0.0.1:8787 trail init --connect TRL-GOOD-C0DE`).+ *+ * Shapes follow the onboarding contract (A1: connect, stages, summary; A2:+ * the workspace connector's brain tools over MCP streamable HTTP, stateless+ * and JSON). Everything it's sent is kept in `log`, in order.+ */+import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";+import type { AddressInfo } from "node:net";++export const GOOD_CODE = "TRL-GOOD-C0DE";+export const TOKEN = "trl_test_token";++export interface Logged {+ method: string;+ path: string;+ auth?: string;+ body: any;+}++export interface FakeTrail {+ url: string;+ log: Logged[];+ close(): Promise<void>;+}++const BRAIN_TOOLS = [+ { name: "list_brains", description: "Remote: the workspace's brains.", inputSchema: { type: "object", properties: {} } },+ { name: "get_context", description: "Remote: rules that apply to a task.", inputSchema: { type: "object", properties: { query: { type: "string" }, brain: { type: "string" } }, required: ["query"] } },+ { name: "search_rules", description: "Remote: search rules.", inputSchema: { type: "object", properties: { query: { type: "string" } }, required: ["query"] } },+ { name: "get_rules", description: "Remote: every rule in a brain.", inputSchema: { type: "object", properties: { brain: { type: "string" } }, required: ["brain"] } },+ // The connector serves agent tools too; only the brain tools may come through.+ { name: "list_agents", description: "Remote: agents.", inputSchema: { type: "object", properties: {} } },+];++function readBody(req: IncomingMessage): Promise<string> {+ return new Promise((resolve) => {+ let s = "";+ req.setEncoding("utf8");+ req.on("data", (d) => (s += d));+ req.on("end", () => resolve(s));+ });+}++function send(res: ServerResponse, status: number, body: unknown): void {+ res.writeHead(status, { "content-type": "application/json" });+ res.end(body === undefined ? "" : JSON.stringify(body));+}++export async function startFakeTrail(port = 0): Promise<FakeTrail> {+ const log: Logged[] = [];+ const server: Server = createServer(async (req, res) => {+ const text = await readBody(req);+ let body: any = null;+ try {+ body = text ? JSON.parse(text) : null;+ } catch {+ /* kept as null */+ }+ const path = new URL(req.url ?? "/", "http://x").pathname;+ const auth = req.headers.authorization;+ log.push({ method: req.method ?? "", path, auth, body });+ const authed = auth === `Bearer ${TOKEN}`;++ if (req.method === "GET" && path === "/__log") return send(res, 200, log);+ if (req.method !== "POST") return send(res, 405, { error: "method not allowed" });++ if (path === "/api/public/cli/connect") {+ if (!body?.code || !body?.repo?.name) return send(res, 400, { error: "bad request", error_code: "invalid_request" });+ const bare = String(body.code).toUpperCase().replace(/^TRL-?/, "").replace(/[-\s]/g, "");+ if (`TRL-${bare.slice(0, 4)}-${bare.slice(4)}` !== GOOD_CODE) return send(res, 410, { error: "That code was already used or has expired.", error_code: "code_invalid" });+ const base = `http://${req.headers.host}`;+ return send(res, 200, {+ token: TOKEN,+ user: { id: "u1", name: "Rushabh", email: "[email protected]" },+ workspace: { id: "w1", name: "Acme", slug: "w1", url: base, invite_url: `${base}/welcome/code/invite` },+ repo: { key: "github.com/acme/retry", ...body.repo },+ repos: ["github.com/acme/retry"],+ });+ }+ if (path === "/api/cli/onboarding/events") {+ if (!authed) return send(res, 401, { error: "invalid token", error_code: "token_invalid" });+ return send(res, 200, { ok: true, stage: body?.stage, repo: body?.repo });+ }+ if (path === "/api/cli/repos/summary") {+ if (!authed) return send(res, 401, { error: "invalid token", error_code: "token_invalid" });+ return send(res, 200, { ok: true, repo: body?.repo, summary_at: new Date().toISOString() });+ }+ if (path === "/api/v1/mcp" || path === "/mcp") {+ if (!authed) return send(res, 401, { error: "invalid_token" });+ if (body?.id === undefined) return send(res, 202, undefined);+ const reply = (result: unknown) => send(res, 200, { jsonrpc: "2.0", id: body.id, result });+ if (body.method === "initialize") return reply({ protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "trail-workspace", version: "0" } });+ if (body.method === "tools/list") return reply({ tools: BRAIN_TOOLS });+ if (body.method === "tools/call") {+ const { name, arguments: args } = body.params ?? {};+ if (name === "get_context")+ return reply({ content: [{ type: "text", text: `Brand brain · rule r1: Write "Trail", never "TRAIL". (asked: ${args?.query})` }], structuredContent: { rules: [{ rule_id: "r1", brain: { name: "Brand" } }] } });+ if (name === "list_brains") return reply({ content: [{ type: "text", text: "Brand (12 rules)" }] });+ return send(res, 200, { jsonrpc: "2.0", id: body.id, error: { code: -32602, message: `unknown tool ${name}` } });+ }+ return send(res, 200, { jsonrpc: "2.0", id: body.id, error: { code: -32601, message: "method not found" } });+ }+ return send(res, 404, { error: "no route" });+ });+ await new Promise<void>((r) => server.listen(port, "127.0.0.1", () => r()));+ const { port: bound } = server.address() as AddressInfo;+ return {+ url: `http://127.0.0.1:${bound}`,+ log,+ close: () => new Promise<void>((r) => server.close(() => r())),+ };+}++// Run by hand: a fake Trail on the port given (default 8787) that prints what it's sent.+if (import.meta.url === `file://${process.argv[1]}`) {+ const t = await startFakeTrail(Number(process.argv[2] ?? 8787));+ console.log(`fake Trail on ${t.url} · code ${GOOD_CODE}`);+ let shown = 0;+ setInterval(() => {+ for (; shown < t.log.length; shown++) {+ const l = t.log[shown]!;+ console.log(`${l.method} ${l.path}${l.auth ? " (bearer)" : ""}\n${JSON.stringify(l.body, null, 2)}`);+ }+ }, 200);+}diff --git a/test/mcp-brains.test.ts b/test/mcp-brains.test.tsnew file mode 100644index 00000000..a18f420a--- /dev/null+++ b/test/mcp-brains.test.ts@@ -0,0 +1,159 @@+/**+ * The local `trail mcp` server serves the workspace's brains once this+ * machine is connected: the connector's four brain tools are listed next to+ * the repo tools and each call is passed to `<trail>/api/v1/mcp` with the+ * stored token. Not connected, nothing changes; connected but offline, the+ * repo tools still answer.+ */+import { test, after } from "node:test";+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { once } from "node:events";+import { buildGraph } from "../src/graph/build.js";+import { BRAIN_TOOL_DEFS } from "../src/mcp/brains.js";+import { startFakeTrail, TOKEN, type FakeTrail } from "./fake-trail-server.js";++let trail: FakeTrail | null = null;+after(async () => {+ await trail?.close();+});++async function rpc(messages: object[], dir: string, env: NodeJS.ProcessEnv, expected: number, extra: string[] = []): Promise<any[]> {+ const child = spawn(process.execPath, ["--import", "tsx", join(process.cwd(), "src", "bin", "trail.ts"), "mcp", dir, ...extra], { stdio: ["pipe", "pipe", "pipe"], env });+ const responses: any[] = [];+ let buf = "";+ child.stdout.on("data", (d) => {+ buf += d.toString();+ let i;+ while ((i = buf.indexOf("\n")) !== -1) {+ const line = buf.slice(0, i).trim();+ buf = buf.slice(i + 1);+ if (line) responses.push(JSON.parse(line));+ }+ });+ for (const m of messages) child.stdin.write(`${JSON.stringify(m)}\n`);+ const deadline = Date.now() + 20000;+ while (responses.length < expected && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50));+ child.kill();+ await once(child, "exit").catch(() => {});+ return responses;+}++const SESSION = [+ { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "t", version: "0" } } },+ { jsonrpc: "2.0", method: "notifications/initialized" },+ { jsonrpc: "2.0", id: 2, method: "tools/list" },+ { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "get_context", arguments: { query: "how do we write the product name" } } },+ { jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "trail_find_code", arguments: { query: "retryDo" } } },+];++async function builtRepo(): Promise<string> {+ const dir = mkdtempSync(join(tmpdir(), "mcp-brains-"));+ writeFileSync(join(dir, "client.ts"), "export function retryDo(n: number): number {\n return n;\n}\n");+ writeFileSync(join(dir, "a.ts"), 'import { retryDo } from "./client";\nexport const a = retryDo(4);\n');+ await buildGraph(dir);+ return dir;+}++function envWith(cloud: object | null): NodeJS.ProcessEnv {+ const home = mkdtempSync(join(tmpdir(), "mcp-brains-home-"));+ const trailHome = join(home, ".trail");+ mkdirSync(trailHome, { recursive: true });+ if (cloud) writeFileSync(join(trailHome, "cloud.json"), JSON.stringify(cloud));+ const env: NodeJS.ProcessEnv = { ...process.env, HOME: home, USERPROFILE: home, TRAIL_HOME: trailHome, DO_NOT_TRACK: "1", TRAIL_INVOKED_AS: "trail" };+ delete env.TRAIL_MCP_URL;+ return env;+}++function cloudFor(url: string, token = TOKEN) {+ return {+ url,+ token,+ user: { name: "R", email: "[email protected]" },+ workspace: { id: "w1", name: "Acme", slug: "w1", url, invite_url: url },+ repos: [],+ linkedAt: 1,+ via: "connect",+ };+}++const BRAINS = ["list_brains", "get_context", "search_rules", "get_rules"];++test("connected: the workspace's brain tools are listed beside the repo tools, and calls go to the workspace with the token", async () => {+ trail = await startFakeTrail();+ const dir = await builtRepo();+ const rs = await rpc(SESSION, dir, envWith(cloudFor(trail.url)), 4);+ const init = rs.find((r) => r.id === 1);+ assert.match(init.result.instructions, /Connected to a Trail workspace: list_brains, get_context/);+ const names = rs.find((r) => r.id === 2).result.tools.map((t: any) => t.name);+ assert.ok(names.includes("trail_find_code"), names.join(","));+ for (const b of BRAINS) assert.ok(names.includes(b), `${b} in ${names.join(",")}`);+ assert.ok(!names.includes("list_agents"), "only the brain tools come through");+ // The connector's own descriptions, when it answers.+ assert.equal(rs.find((r) => r.id === 2).result.tools.find((t: any) => t.name === "get_context").description, "Remote: rules that apply to a task.");++ const call = rs.find((r) => r.id === 3).result;+ assert.equal(call.isError, false);+ assert.match(call.content[0].text, /^Brand brain · rule r1: .*\(asked: how do we write the product name\)$/);+ assert.deepEqual(call.structuredContent, { rules: [{ rule_id: "r1", brain: { name: "Brand" } }] });+ const local = rs.find((r) => r.id === 4).result;+ assert.equal(local.isError, false);+ assert.match(local.content[0].text, /retryDo/);++ const mcp = trail.log.filter((l) => l.path === "/api/v1/mcp");+ assert.ok(mcp.length >= 3);+ assert.ok(mcp.every((l) => l.auth === `Bearer ${TOKEN}`));+ assert.equal(mcp[0]!.body.method, "initialize");+ assert.deepEqual(mcp.find((l) => l.body.method === "tools/call")!.body.params, { name: "get_context", arguments: { query: "how do we write the product name" } });+});++test("connected but offline: the brain tools are listed and answer with a soft error; the repo tools still work", async () => {+ const dir = await builtRepo();+ const rs = await rpc(SESSION, dir, envWith(cloudFor("http://127.0.0.1:9")), 4);+ const tools = rs.find((r) => r.id === 2).result.tools;+ for (const b of BRAINS) assert.ok(tools.some((t: any) => t.name === b));+ assert.equal(tools.find((t: any) => t.name === "get_context").description, BRAIN_TOOL_DEFS[1]!.description);+ const call = rs.find((r) => r.id === 3).result;+ assert.equal(call.isError, true);+ assert.match(call.content[0].text, /couldn't reach your Trail workspace · the repo tools still work/);+ assert.equal(rs.find((r) => r.id === 4).result.isError, false);+});++test("a token the workspace won't take says how to reconnect", async () => {+ trail ??= await startFakeTrail();+ const dir = await builtRepo();+ const rs = await rpc(SESSION, dir, envWith(cloudFor(trail.url, "trl_revoked")), 4);+ const call = rs.find((r) => r.id === 3).result;+ assert.equal(call.isError, true);+ assert.match(call.content[0].text, /token was not accepted; run `trail init --connect <code>`/);+});++test("not connected: no brain tools, and the instructions are what they always were", async () => {+ const dir = await builtRepo();+ const rs = await rpc(SESSION.slice(0, 3), dir, envWith(null), 2);+ const names = rs.find((r) => r.id === 2).result.tools.map((t: any) => t.name);+ assert.ok(names.includes("trail_find_code"));+ for (const b of BRAINS) assert.ok(!names.includes(b));+ assert.doesNotMatch(rs.find((r) => r.id === 1).result.instructions, /Trail workspace/);+});++test("trail mcp --brains, Claude Code's entry: the brain tools and nothing of the repo's", async () => {+ trail ??= await startFakeTrail();+ const dir = await builtRepo();+ const rs = await rpc(SESSION, dir, envWith(cloudFor(trail.url)), 4, ["--brains"]);+ const names = rs.find((r) => r.id === 2).result.tools.map((t: any) => t.name);+ assert.deepEqual(names.sort(), [...BRAINS].sort());+ assert.match(rs.find((r) => r.id === 1).result.instructions, /^Connected to a Trail workspace/);+ assert.doesNotMatch(rs.find((r) => r.id === 1).result.instructions, /indexed by/);+ assert.equal(rs.find((r) => r.id === 3).result.isError, false);+ const repoTool = rs.find((r) => r.id === 4).result;+ assert.equal(repoTool.isError, true);+ assert.match(repoTool.content[0].text, /brain tools only/);++ const off = await rpc(SESSION.slice(0, 3), dir, envWith(null), 2, ["--brains"]);+ assert.deepEqual(off.find((r) => r.id === 2).result.tools, []);+ assert.match(off.find((r) => r.id === 1).result.instructions, /Not connected to a Trail workspace: run `trail init --connect <code>`/);+});diff --git a/test/trail-connect-cli.test.ts b/test/trail-connect-cli.test.tsnew file mode 100644index 00000000..3539da88--- /dev/null+++ b/test/trail-connect-cli.test.ts@@ -0,0 +1,239 @@+/**+ * `trail init --connect <CODE>` end to end, against a fake Trail over real+ * HTTP: the code is claimed, the token saved where `trail login` keeps it,+ * the page's stages go up in order around init's usual work, and one summary+ * of the repo (tokens on one lookup, learnings, teammates' branches) goes up+ * before `done`. A wrong code stops before anything is written; an offline+ * Trail doesn't stop init; without --connect, nothing goes anywhere.+ */+import { test, after } from "node:test";+import assert from "node:assert/strict";+import { spawn, spawnSync } from "node:child_process";+import { existsSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { GOOD_CODE, TOKEN, startFakeTrail, type FakeTrail } from "./fake-trail-server.js";+import { writeNote } from "../src/notes/notes.js";+import { buildGraph } from "../src/graph/build.js";+import { BRAND_ENV } from "../src/brand.js";++process.env.DO_NOT_TRACK = "1";+process.env[BRAND_ENV] = "trail";++let trail: FakeTrail | null = null;+after(async () => {+ await trail?.close();+});++function git(cwd: string, ...args: string[]): string {+ const r = spawnSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd, encoding: "utf8" });+ if (r.status !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr}`);+ return r.stdout;+}++/** A distinctive line of code, so the test can tell if any code went up. */+const CODE_MARK = "return attempts * 7919";++/** A "GitHub" remote with a hub file, me with history on it, and Kumar's fresh branch changing it. */+function repoWithTeam(): string {+ const root = mkdtempSync(join(tmpdir(), "connect-cli-"));+ const bare = join(root, "retry.git");+ git(root, "init", "-q", "--bare", "-b", "main", bare);+ const seed = join(root, "seed");+ git(root, "init", "-q", "-b", "main", seed);+ const filler = Array.from({ length: 300 }, (_, i) => `export function helper${i}(x: number): number {\n return x * ${i} + ${i};\n}\n`).join("\n");+ writeFileSync(join(seed, "client.ts"), `export function retryDo(attempts: number): number {\n ${CODE_MARK};\n}\n\n${filler}`);+ for (const f of ["a", "b", "c"]) writeFileSync(join(seed, `${f}.ts`), `import { retryDo } from "./client";\nexport function use${f}() {\n return retryDo(4);\n}\n`);+ git(seed, "add", "-A");+ git(seed, "-c", "user.name=Seed", "-c", "user.email=s@x", "commit", "-qm", "init");+ git(seed, "push", "-q", bare, "main");+ const clone = (who: string, name: string) => {+ const d = join(root, who);+ git(root, "clone", "-q", bare, d);+ git(d, "remote", "set-url", "origin", "https://github.com/acme/retry.git");+ git(d, "config", `url.${bare}.insteadOf`, "https://github.com/acme/retry.git");+ git(d, "config", "user.name", name);+ git(d, "config", "user.email", `${who}@acme.test`);+ git(d, "remote", "set-head", "origin", "main");+ return d;+ };+ const me = clone("rushabh", "Rushabh Nagda");+ writeFileSync(join(me, "client.ts"), readFileSync(join(me, "client.ts"), "utf8").replace("attempts * 7919", "attempts * 7907"));+ writeNote(me, { title: "Keep retryDo() at 4 attempts", body: "## Decided\n- Keep retryDo() at 4 attempts.\n\n_Told to Claude in 3 past sessions here, most recently on Oct 9._", author: "Rushabh", date: "2026-10-09", touches: ["client.ts"] });+ git(me, "add", "-A");+ git(me, "commit", "-qm", "Tune retryDo");++ const kumar = clone("kumar", "Kumar S");+ git(kumar, "checkout", "-q", "-b", "kumar/retry");+ writeFileSync(join(kumar, "client.ts"), readFileSync(join(kumar, "client.ts"), "utf8").replace("retryDo(attempts: number)", "retryDo(attempts: number, cap = 10)"));+ git(kumar, "commit", "-qam", "Raise the retry count to 10");+ git(kumar, "push", "-q", "origin", "kumar/retry");+ git(me, "fetch", "-q", "origin");+ return me;+}++function run(args: string[], env: NodeJS.ProcessEnv): Promise<{ status: number | null; stderr: string; stdout: string }> {+ return new Promise((resolve) => {+ const child = spawn(process.execPath, ["--import", "tsx", join(process.cwd(), "src", "bin", "trail.ts"), ...args], { env, stdio: ["ignore", "pipe", "pipe"] });+ let stdout = "";+ let stderr = "";+ child.stdout.on("data", (d) => (stdout += d));+ child.stderr.on("data", (d) => (stderr += d));+ child.on("close", (status) => resolve({ status, stdout, stderr }));+ });+}++function envFor(url: string): NodeJS.ProcessEnv {+ const home = mkdtempSync(join(tmpdir(), "connect-cli-home-"));+ return {+ ...process.env,+ HOME: home,+ USERPROFILE: home,+ TRAIL_HOME: join(home, ".trail"),+ TRAIL_URL: url,+ // No past-session or PR-review read (those ask Claude and GitHub), and no git fetch.+ TRAIL_NO_FETCH: "1",+ DO_NOT_TRACK: "1",+ TRAIL_INVOKED_AS: "trail",+ };+}++test("init --connect claims the code, sends the stages in order around init, and a summary with no code in it", async () => {+ trail = await startFakeTrail();+ const repo = repoWithTeam();+ // Built here: init's own build runs `node --import tsx` from inside the repo, where tsx isn't installed.+ await buildGraph(repo);+ const env = envFor(trail.url);+ const r = await run(["init", repo, "--connect", "trl-good-c0de", "--agents", "claude", "--no-global"], env);+ assert.equal(r.status, 0, r.stderr);+ assert.match(r.stderr, /^✓ connected to workspace Acme$/m);+ // init's own output is all still there.+ assert.match(r.stderr, /✓ graph ready · /);+ assert.match(r.stderr, /✓ claude/);+ assert.match(r.stderr, /✓ sent Acme a summary: one lookup saved \d+% of the tokens, 1 learning, 1 teammate branch on your files/);++ const log = trail.log.filter((l) => l.path.startsWith("/api/"));+ assert.deepEqual(+ log.map((l) => (l.path === "/api/cli/onboarding/events" ? `stage:${l.body.stage}` : l.path)),+ ["/api/public/cli/connect", "stage:connected", "stage:mapped", "stage:learned", "/api/cli/repos/summary", "stage:done"],+ );+ const connect = log[0]!;+ assert.equal(connect.body.code, GOOD_CODE);+ assert.deepEqual(connect.body.repo, { name: "retry", remote_url: "https://github.com/acme/retry" });+ assert.equal(typeof connect.body.machine, "string");+ assert.ok(log.slice(1).every((l) => l.auth === `Bearer ${TOKEN}`));++ const mapped = log.find((l) => l.body?.stage === "mapped")!;+ assert.ok(mapped.body.data.nodes > 0 && mapped.body.data.edges > 0 && mapped.body.data.files === 4, JSON.stringify(mapped.body.data));+ const learned = log.find((l) => l.body?.stage === "learned")!;+ assert.deepEqual(learned.body.data, { learnings: 1, sessions: 3 });++ const summary = log.find((l) => l.path === "/api/cli/repos/summary")!.body;+ assert.deepEqual(summary.repo, { name: "retry", remote_url: "https://github.com/acme/retry" });+ assert.equal(summary.tokens.symbol, "retryDo");+ assert.ok(summary.tokens.saved > 0 && summary.tokens.baseline > summary.tokens.pack);+ assert.deepEqual(summary.learnings, [{ title: "Keep retryDo() at 4 attempts", body: "Keep retryDo() at 4 attempts.", sessions: 3 }]);+ assert.equal(summary.sessions, 3);+ assert.equal(summary.teammates.length, 1);+ assert.deepEqual(+ { ...summary.teammates[0], pushed_at: undefined },+ {+ name: "Kumar S",+ email: "[email protected]",+ branch: "kumar/retry",+ files: ["client.ts"],+ change: "Raise the retry count to 10",+ commits: 1,+ conflict: 'Changes retryDo in client.ts, which your learning "Keep retryDo() at 4 attempts" is about.',+ pushed_at: undefined,+ },+ );+ // Route B: titles, counts and names. No code, from this clone or Kumar's branch.+ const everything = JSON.stringify(trail.log);+ for (const code of ["attempts *", "export function", "helper1", "cap = 10"]) assert.ok(!everything.includes(code), `sent code: ${code}`);++ // The token is kept where `trail login` keeps it, owner-only.+ const cloudPath = join(env.TRAIL_HOME!, "cloud.json");+ const cloud = JSON.parse(readFileSync(cloudPath, "utf8"));+ assert.equal(cloud.token, TOKEN);+ assert.equal(cloud.via, "connect");+ assert.equal(cloud.workspace.name, "Acme");+ assert.deepEqual(cloud.repos, []);+ if (process.platform !== "win32") assert.equal(statSync(cloudPath).mode & 0o777, 0o600);++ // Connected, the workspace commands show in help.+ const help = await run(["--help"], env);+ assert.match(help.stdout, /workspace/);+});++test("a wrong or spent code stops before anything is written", async () => {+ trail ??= await startFakeTrail();+ const repo = repoWithTeam();+ const env = envFor(trail.url);+ const r = await run(["init", repo, "--connect", "TRL-USED-C0DE", "--agents", "claude", "--no-global"], env);+ assert.equal(r.status, 1);+ assert.match(r.stderr, /✗ that code was already used, has expired, or isn't right · get a new code at http:\/\/127\.0\.0\.1:\d+\/welcome\/code/);+ assert.equal(existsSync(join(repo, ".claude", "settings.json")), false);+ assert.equal(existsSync(join(env.TRAIL_HOME!, "cloud.json")), false);++ const bad = await run(["init", repo, "--connect", "nope"], env);+ assert.equal(bad.status, 1);+ assert.match(bad.stderr, /isn't a Trail code/);+});++test("offline, init still sets the repo up and says how to connect later", async () => {+ const repo = repoWithTeam();+ const env = envFor("http://127.0.0.1:9");+ const r = await run(["init", repo, "--connect", GOOD_CODE, "--agents", "claude", "--no-global", "--no-build"], env);+ assert.equal(r.status, 0, r.stderr);+ assert.match(r.stderr, /couldn't reach Trail .* setting up this repo anyway; run trail init --connect TRL-GOOD-C0DE again to connect/);+ assert.ok(existsSync(join(repo, ".claude", "settings.json")));+ assert.equal(existsSync(join(env.TRAIL_HOME!, "cloud.json")), false);+});++test("without --connect, init sends nothing anywhere and prints what it always did", async () => {+ trail ??= await startFakeTrail();+ const before = trail.log.length;+ const repo = repoWithTeam();+ const env = envFor(trail.url);+ const r = await run(["init", repo, "--agents", "claude", "--no-global", "--no-build"], env);+ assert.equal(r.status, 0, r.stderr);+ assert.equal(trail.log.length, before);+ assert.doesNotMatch(r.stderr, /connected to workspace|summary/);+ assert.equal(existsSync(join(env.TRAIL_HOME!, "cloud.json")), false);+});++test("connected with Claude Code wired, Claude Code gets one user-level trail entry that serves the brains, and logout takes it out", async () => {+ trail ??= await startFakeTrail();+ const repo = repoWithTeam();+ await buildGraph(repo);+ const env = { ...envFor(trail.url), GRAFT_MCP_NPX: "1" };+ const r = await run(["init", repo, "--connect", GOOD_CODE, "--agents", "claude"], env);+ assert.equal(r.status, 0, r.stderr);+ assert.match(r.stderr, /✓ Claude Code gets your workspace's brains in every project · restart it to pick them up$/m);+ const claudeJson = join(env.HOME!, ".claude.json");+ assert.deepEqual(JSON.parse(readFileSync(claudeJson, "utf8")).mcpServers.trail, { command: "npx", args: ["-y", "@trailhq/trail-code", "mcp", "--brains"] });++ // A plain init later keeps it: it isn't the repo-tools server trail stopped giving Claude Code.+ const again = await run(["init", repo, "--agents", "claude", "--no-build"], env);+ assert.equal(again.status, 0, again.stderr);+ assert.ok(JSON.parse(readFileSync(claudeJson, "utf8")).mcpServers.trail);++ const out = await run(["logout"], env);+ assert.equal(out.status, 0, out.stderr);+ assert.equal(JSON.parse(readFileSync(claudeJson, "utf8")).mcpServers.trail, undefined);+ assert.equal(existsSync(join(env.TRAIL_HOME!, "cloud.json")), false);+});++test("--server points the connect at another Trail, and the connection remembers it", async () => {+ trail ??= await startFakeTrail();+ const repo = repoWithTeam();+ const env = envFor("http://127.0.0.1:9");+ const r = await run(["init", repo, "--connect", GOOD_CODE, "--server", `${trail.url}/`, "--agents", "claude", "--no-global", "--no-build"], env);+ assert.equal(r.status, 0, r.stderr);+ assert.match(r.stderr, /✓ connected to workspace Acme/);+ assert.equal(JSON.parse(readFileSync(join(env.TRAIL_HOME!, "cloud.json"), "utf8")).url, trail.url);+ const bad = await run(["init", repo, "--connect", GOOD_CODE, "--server", "dev.trailhq.com"], env);+ assert.equal(bad.status, 1);+ assert.match(bad.stderr, /--server takes a URL/);+});diff --git a/test/trail-connect.test.ts b/test/trail-connect.test.tsnew file mode 100644index 00000000..e28c32da--- /dev/null+++ b/test/trail-connect.test.ts@@ -0,0 +1,345 @@+/**+ * `trail init --connect <CODE>`, piece by piece: the code, the claim, the+ * stages and summary as they go to Trail, and what the summary is made of+ * (one lookup's tokens saved, the learnings' titles, teammates' branches+ * from git). Route B: nothing in it is code, a diff or session text.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { BRAND_ENV } from "../src/brand.js";+import { formatAsk, ask } from "../src/ask/ask.js";+import { buildGraph } from "../src/graph/build.js";+import {+ claimConnectCode,+ conflictLine,+ learningTerms,+ learningsSummary,+ normalizeCode,+ OnboardingReporter,+ parseAskSavings,+ repoRef,+ sessionsIn,+ shortBody,+ teammatesFromGit,+ tokensOnOneLookup,+} from "../src/cloud/onboarding.js";+import { readCloud, writeCloud, type Cloud } from "../src/cloud/workspace.js";+import { inWorkspace, recordActivity } from "../src/cloud/workspace-sync.js";+import { cloudLines } from "../src/cloud/nudge.js";+import { writeNote, listNotes } from "../src/notes/notes.js";+import { existsSync } from "node:fs";++process.env.DO_NOT_TRACK = "1";+process.env[BRAND_ENV] = "trail";+process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "connect-trail-home-"));++function git(cwd: string, ...args: string[]): string {+ const r = spawnSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd, encoding: "utf8" });+ if (r.status !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr}`);+ return r.stdout;+}++const json = (status: number, b: unknown) => new Response(JSON.stringify(b), { status, headers: { "content-type": "application/json" } });++/* the code ----------------------------------------------------------------- */++test("a code is read however it was pasted, and anything else is refused", () => {+ for (const raw of ["TRL-7F2A-K9QD", "trl-7f2a-k9qd", " TRL7F2AK9QD ", "7F2A-K9QD", "7f2ak9qd", "TRL 7F2A K9QD"]) assert.equal(normalizeCode(raw), "TRL-7F2A-K9QD", raw);+ for (const bad of ["", "TRL-7F2A", "TRL-7F2A-K9QD-XX", "hello world", "TRL-7F2A-K9Q!"]) assert.equal(normalizeCode(bad), null, bad);+});++test("the repo goes up as a name and a clean URL: never a path here, never a token in the remote", () => {+ const dir = mkdtempSync(join(tmpdir(), "connect-ref-"));+ git(dir, "init", "-q", "-b", "main");+ git(dir, "remote", "add", "origin", "https://x-access-token:[email protected]/Acme/Retry.git");+ const ref = repoRef(dir);+ assert.deepEqual(ref, { name: "Retry", remote_url: "https://github.com/acme/retry" });+ assert.ok(!JSON.stringify(ref).includes("SECRET"));+ assert.ok(!JSON.stringify(ref).includes(dir));++ const local = mkdtempSync(join(tmpdir(), "connect-local-"));+ git(local, "init", "-q", "-b", "main");+ const l = repoRef(local);+ assert.equal(l.remote_url, undefined);+ assert.ok(l.name);+});++/* the claim ---------------------------------------------------------------- */++test("claiming a code gives a connection with no repos picked, marked as made by --connect", async () => {+ const sent: any[] = [];+ const fetchImpl = (async (url: string, init: RequestInit) => {+ sent.push({ url, body: JSON.parse(String(init.body)) });+ return json(200, {+ token: "trl_abc",+ user: { id: "u1", name: "Rushabh", email: "[email protected]" },+ workspace: { id: "w1", name: "Acme", slug: "w1", url: "http://trail.test", invite_url: "http://trail.test/welcome/code/invite" },+ repo: { key: "github.com/acme/retry", name: "retry", remote_url: "https://github.com/acme/retry" },+ repos: ["github.com/acme/retry"],+ });+ }) as typeof fetch;+ const got = await claimConnectCode("http://trail.test", "TRL-7F2A-K9QD", { machine: "Rushabh's MacBook", repo: { name: "retry", remote_url: "https://github.com/acme/retry" } }, { fetchImpl, now: 5 });+ assert.ok("cloud" in got);+ assert.equal(sent[0].url, "http://trail.test/api/public/cli/connect");+ assert.deepEqual(sent[0].body, { code: "TRL-7F2A-K9QD", machine: "Rushabh's MacBook", repo: { name: "retry", remote_url: "https://github.com/acme/retry" } });+ const c = got.cloud;+ assert.equal(c.token, "trl_abc");+ assert.equal(c.workspace.name, "Acme");+ assert.equal(c.via, "connect");+ // The full learnings sync stays off: only the summary goes up from a machine connected this way.+ assert.deepEqual(c.repos, []);+ assert.equal(c.linkedAt, 5);+});++test("a connect answer without a slug or urls still makes a connection readCloud accepts", async () => {+ const fetchImpl = (async () => json(200, { token: "trl_abc", workspace: { id: "w1", name: "Acme" }, user: { name: "R" } })) as unknown as typeof fetch;+ const got = await claimConnectCode("http://trail.test", "TRL-7F2A-K9QD", { machine: "m", repo: { name: "retry" } }, { fetchImpl });+ assert.ok("cloud" in got);+ writeCloud(got.cloud);+ assert.equal(readCloud()?.workspace.slug, "w1");+});++test("a used, expired or wrong code is refused; an unreachable Trail is offline, not refused", async () => {+ const answer = (status: number) => (async () => json(status, { error: "x", error_code: "code_invalid" })) as unknown as typeof fetch;+ for (const status of [400, 404, 410]) {+ const got = await claimConnectCode("http://trail.test", "TRL-7F2A-K9QD", { machine: "m", repo: { name: "r" } }, { fetchImpl: answer(status) });+ assert.ok("reason" in got && got.reason === "invalid", String(status));+ }+ const revoked = await claimConnectCode("http://trail.test", "TRL-7F2A-K9QD", { machine: "m", repo: { name: "r" } }, { fetchImpl: answer(403) });+ assert.ok("reason" in revoked && revoked.reason === "invalid" && /no longer in that workspace/.test(revoked.error));+ const down = await claimConnectCode("http://trail.test", "TRL-7F2A-K9QD", { machine: "m", repo: { name: "r" } }, { fetchImpl: answer(502) });+ assert.ok("reason" in down && down.reason === "offline");+ const offline = await claimConnectCode("http://trail.test", "TRL-7F2A-K9QD", { machine: "m", repo: { name: "r" } }, {+ fetchImpl: (async () => {+ throw new TypeError("fetch failed");+ }) as unknown as typeof fetch,+ });+ assert.ok("reason" in offline && offline.reason === "offline");+});++/* the stages --------------------------------------------------------------- */++const CLOUD: Cloud = {+ url: "http://trail.test",+ token: "trl_abc",+ user: { name: "R", email: "[email protected]" },+ workspace: { id: "w1", name: "Acme", slug: "w1", url: "http://trail.test", invite_url: "http://trail.test" },+ repos: [],+ linkedAt: 1,+ via: "connect",+};++test("stages and the summary go up in order, with the token, and the repo and machine on each stage", async () => {+ const seen: Array<{ path: string; body: any; auth?: string }> = [];+ const fetchImpl = (async (url: string, init: RequestInit) => {+ seen.push({ path: new URL(url).pathname, body: JSON.parse(String(init.body)), auth: (init.headers as Record<string, string>).authorization });+ // Answer the first one slowest: order must not depend on who answers first.+ if (seen.length === 1) await new Promise((r) => setTimeout(r, 30));+ return json(200, { ok: true });+ }) as typeof fetch;+ const r = new OnboardingReporter(CLOUD, { name: "retry", remote_url: "https://github.com/acme/retry" }, { fetchImpl, machine: "MacBook" });+ void r.stage("connected");+ void r.stage("mapped", { nodes: 97, edges: 241, files: 6 });+ void r.stage("learned", { learnings: 2, sessions: 3 });+ assert.equal(await r.summary({ tokens: null, learnings: [], teammates: [] }), true);+ await r.stage("done");+ await r.flush();+ assert.deepEqual(+ seen.map((s) => (s.path === "/api/cli/onboarding/events" ? s.body.stage : s.path)),+ ["connected", "mapped", "learned", "/api/cli/repos/summary", "done"],+ );+ assert.ok(seen.every((s) => s.auth === "Bearer trl_abc"));+ assert.deepEqual(seen[1]!.body, { repo: { name: "retry", remote_url: "https://github.com/acme/retry" }, stage: "mapped", machine: "MacBook", data: { nodes: 97, edges: 241, files: 6 } });+});++test("offline, the first stage that can't reach Trail turns the rest off, and nothing throws", async () => {+ let calls = 0;+ const fetchImpl = (async () => {+ calls++;+ throw new TypeError("fetch failed");+ }) as unknown as typeof fetch;+ const r = new OnboardingReporter(CLOUD, { name: "retry" }, { fetchImpl });+ assert.equal(await r.stage("connected"), false);+ assert.equal(await r.stage("mapped", {}), false);+ assert.equal(await r.summary({ tokens: null, learnings: [], teammates: [] }), false);+ await r.flush();+ assert.equal(calls, 1);+});++test("an HTTP error is that call's alone: the next one still goes", async () => {+ let calls = 0;+ const fetchImpl = (async () => (++calls === 1 ? json(500, { error: "boom" }) : json(200, { ok: true }))) as unknown as typeof fetch;+ const r = new OnboardingReporter(CLOUD, { name: "retry" }, { fetchImpl });+ assert.equal(await r.stage("connected"), false);+ assert.equal(await r.stage("mapped", {}), true);+});++/* tokens ------------------------------------------------------------------- */++test("the tokens numbers are the ones ask's own savings line prints", () => {+ const line =+ "[trail] tokens saved ≈ 15,392 (88%) — this pack ≈ 2,048 tok vs reading the 3 source file(s) whole ≈ 17,440 tok. Estimate (baseline = those files read in full).";+ assert.deepEqual(parseAskSavings(`${line}\n\nbody`), { saved: 15392, pct: 88, pack: 2048, files: 3, baseline: 17440 });+ assert.equal(parseAskSavings("no line here"), null);+});++test("one real lookup on the fresh map: the most central symbol, and what reading the map saved", async () => {+ const dir = mkdtempSync(join(tmpdir(), "connect-tokens-"));+ // A hub everyone calls, in a big file, so reading it whole costs far more than the pack.+ const filler = Array.from({ length: 400 }, (_, i) => `export function helper${i}(x: number): number {\n return x * ${i} + ${i};\n}\n`).join("\n");+ writeFileSync(join(dir, "client.ts"), `export function retryDo(attempts: number): number {\n let n = 0;\n for (let i = 0; i < attempts; i++) n += i;\n return n;\n}\n\n${filler}`);+ for (const f of ["a", "b", "c", "d"]) writeFileSync(join(dir, `${f}.ts`), `import { retryDo } from "./client";\nexport function use${f}() {\n return retryDo(4);\n}\n`);+ await buildGraph(dir);+ const t = tokensOnOneLookup(dir);+ assert.ok(t, "a lookup with a saving");+ assert.equal(t.symbol, "retryDo");+ assert.equal(t.question, "how retryDo works");+ assert.ok(t.saved > 0 && t.baseline > t.pack && t.pct > 0 && t.pct <= 100 && t.files >= 1);+ // The same numbers the agent sees on that query.+ assert.deepEqual(parseAskSavings(formatAsk(ask(dir, "how does retryDo work", { source: true, limit: 5 }))), { saved: t.saved, pct: t.pct, pack: t.pack, files: t.files, baseline: t.baseline });+ assert.equal(tokensOnOneLookup(mkdtempSync(join(tmpdir(), "connect-nograph-"))), null);+});++/* learnings ---------------------------------------------------------------- */++test("a learning goes up as its title, one short line and its session count: no code block, no provenance line", () => {+ const body =+ "## Decided\n- Keep defaultRetryMax at 4: ten retries can hold one Do() call for over an hour.\n\n```go\nconst defaultRetryMax = 4\n```\n\n_Told to Claude in 3 past sessions here, most recently on Oct 9._";+ assert.equal(shortBody(body), "Keep defaultRetryMax at 4: ten retries can hold one Do() call for over an hour.");+ assert.equal(sessionsIn(body), 3);+ assert.equal(shortBody("```\ncode only\n```\nPlain line after."), "Plain line after.");+ assert.equal(shortBody("x".repeat(500)).length, 200);+});++test("the summary's learnings are the team's: what init just learned, else what .trail/learnings has; never a personal one", () => {+ const dir = mkdtempSync(join(tmpdir(), "connect-learn-"));+ git(dir, "init", "-q", "-b", "main");+ const team = writeNote(dir, { title: "Run go test -race before saying done", body: "## Decided\n- Run `go test -race ./...` before saying done.\n\n_Told to Claude in 2 past sessions here, most recently on Oct 9._", author: "R", date: "2026-10-09", touches: [] });+ const mine = writeNote(dir, { title: "My shell aliases", body: "## Decided\n- zsh needs interactivecomments.", author: "R", date: "2026-10-09" }, "personal");+ assert.deepEqual(learningsSummary(dir, [{ note: team, sessions: 3 }, { note: mine, sessions: 2 }]), [+ { title: "Run go test -race before saying done", body: "Run `go test -race ./...` before saying done.", sessions: 3 },+ ]);+ // Nothing learned this run: the repo's own, sessions read from the line under each.+ assert.deepEqual(learningsSummary(dir, []), [{ title: "Run go test -race before saying done", body: "Run `go test -race ./...` before saying done.", sessions: 2 }]);+});++/* teammates ---------------------------------------------------------------- */++const DAY = 24 * 60 * 60 * 1000;++/** A bare "GitHub" remote and clones of it, one per person, like trail-cloud.test.ts. */+function team(): { root: string; bare: string; clone: (who: string, name: string) => string } {+ const root = mkdtempSync(join(tmpdir(), "connect-team-"));+ const bare = join(root, "retry.git");+ git(root, "init", "-q", "--bare", "-b", "main", bare);+ const seed = join(root, "seed");+ git(root, "init", "-q", "-b", "main", seed);+ writeFileSync(join(seed, "client.go"), "package retry\n\nconst defaultRetryMax = 4\n");+ writeFileSync(join(seed, "backoff.go"), "package retry\n");+ writeFileSync(join(seed, "README.md"), "# retry\n");+ git(seed, "add", "-A");+ git(seed, "-c", "user.name=Seed", "-c", "user.email=s@x", "commit", "-qm", "init");+ git(seed, "push", "-q", bare, "main");+ const clone = (who: string, name: string) => {+ const d = join(root, who);+ git(root, "clone", "-q", bare, d);+ git(d, "remote", "set-url", "origin", "https://github.com/acme/retry.git");+ git(d, "config", `url.${bare}.insteadOf`, "https://github.com/acme/retry.git");+ git(d, "config", "user.name", name);+ git(d, "config", "user.email", `${who}@acme.test`);+ git(d, "remote", "set-head", "origin", "main");+ return d;+ };+ return { root, bare, clone };+}++/** Commit `files` on a new branch in `dir` and push it, dated `at`. */+function pushBranch(dir: string, branch: string, files: Record<string, string>, subject: string, at = Date.now()): void {+ git(dir, "checkout", "-q", "-b", branch, "origin/main");+ for (const [f, text] of Object.entries(files)) writeFileSync(join(dir, f), text);+ git(dir, "add", "-A");+ const date = new Date(at).toISOString();+ const r = spawnSync("git", ["-c", "commit.gpgsign=false", "commit", "-qm", subject], { cwd: dir, encoding: "utf8", env: { ...process.env, GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date } });+ assert.equal(r.status, 0, r.stderr);+ git(dir, "push", "-q", "origin", branch);+}++test("teammates: others' branches pushed in the last 14 days that change the files you work on, with what they change", () => {+ const { clone } = team();+ const me = clone("rushabh", "Rushabh Nagda");+ const kumar = clone("kumar", "Kumar S");+ const priya = clone("priya", "Priya R");+ const old = clone("olga", "Olga O");++ // What I work on: client.go, committed on my own pushed branch.+ pushBranch(me, "rushabh/retry-docs", { "client.go": "package retry\n\n// Keep it at 4.\nconst defaultRetryMax = 4\n" }, "Document the retry default");+ git(me, "checkout", "-q", "main");++ pushBranch(kumar, "kumar/retry", { "client.go": "package retry\n\nconst defaultRetryMax = 10\n" }, "Raise defaultRetryMax to 10");+ pushBranch(priya, "priya/readme", { "README.md": "# retry\n\nMore docs.\n" }, "Docs: more README");+ pushBranch(old, "olga/client", { "client.go": "package retry\n\nconst defaultRetryMax = 5\n" }, "Try 5", Date.now() - 20 * DAY);++ const rule = writeNote(me, { title: "Keep defaultRetryMax at 4", body: "## Decided\n- Keep it at 4.", author: "Rushabh", date: "2026-10-09", touches: ["client.go"] });+ const got = teammatesFromGit(me, { learnings: [rule] });+ assert.equal(got.length, 1, JSON.stringify(got, null, 2));+ const k = got[0]!;+ assert.equal(k.name, "Kumar S");+ assert.equal(k.email, "[email protected]");+ assert.equal(k.branch, "kumar/retry");+ assert.deepEqual(k.files, ["client.go"]);+ assert.equal(k.change, "Raise defaultRetryMax to 10");+ assert.equal(k.commits, 1);+ assert.equal(k.conflict, 'Changes defaultRetryMax in client.go, which your learning "Keep defaultRetryMax at 4" is about.');+ assert.ok(Math.abs(Date.parse(k.pushed_at) - Date.now()) < DAY);+ // Names, branch and file names and subjects only: no diff.+ assert.ok(!JSON.stringify(got).includes("defaultRetryMax = 10"));+});++test("with no history of your own here, teammates are matched on the repo's busiest files", () => {+ const { clone } = team();+ const kumar = clone("kumar", "Kumar S");+ pushBranch(kumar, "kumar/retry", { "client.go": "package retry\n\nconst defaultRetryMax = 10\n" }, "Raise defaultRetryMax to 10");+ const fresh = clone("newbie", "New Person");+ const got = teammatesFromGit(fresh);+ assert.deepEqual(got.map((t) => t.branch), ["kumar/retry"]);+ assert.deepEqual(got[0]!.files, ["client.go"]);+});++test("a conflict needs the branch to change a name the learning is about, not just its file", () => {+ const { clone } = team();+ const me = clone("rushabh", "Rushabh Nagda");+ const kumar = clone("kumar", "Kumar S");+ const priya = clone("priya", "Priya R");+ pushBranch(kumar, "kumar/retry", { "client.go": "package retry\n\nconst defaultRetryMax = 10\n" }, "Raise defaultRetryMax to 10");+ pushBranch(priya, "priya/jitter", { "client.go": "package retry\n\nconst defaultRetryMax = 4\n\nfunc Jitter() {}\n" }, "Add jitter");+ git(me, "fetch", "-q", "origin");+ const rule = { title: "Keep defaultRetryMax at 4", body: "## Decided\n- Ten retries can hold one Do() call for over an hour.", author: "", date: "", touches: ["client.go"], path: "", scope: "repo" as const };+ assert.deepEqual(learningTerms(rule).sort(), ["Do", "defaultRetryMax"]);+ assert.equal(conflictLine(me, "origin/main", "origin/kumar/retry", ["client.go"], [rule]), 'Changes defaultRetryMax in client.go, which your learning "Keep defaultRetryMax at 4" is about.');+ assert.equal(conflictLine(me, "origin/main", "origin/priya/jitter", ["client.go"], [rule]), undefined, "same file, different code");+ assert.equal(conflictLine(me, "origin/main", "origin/kumar/retry", ["client.go"], [{ ...rule, title: "Keep the retry count low", body: "## Decided\n- Keep it low." }]), undefined, "a learning naming nothing code-like");+ assert.deepEqual(learningTerms({ ...rule, title: "x", body: "", touches: ["client.go#Client.Do"] }), ["Do"]);+});++/* a connection made by --connect ------------------------------------------- */++test("a machine connected by --connect never syncs learnings or records searches, and is never asked to add a repo", () => {+ const { clone } = team();+ const me = clone("rushabh", "Rushabh Nagda");+ writeNote(me, { title: "A team learning", body: "## Decided\n- x", author: "R", date: "2026-10-09" });+ const key = "github.com/acme/retry";+ const cloud: Cloud = { ...CLOUD, repos: [key] };+ writeCloud(cloud);+ assert.equal(inWorkspace(me, cloud), false);+ recordActivity({ repo: key, kind: "search", asker: "R", session: "s", query: "secret question", files: [], shown_paths: [], shown_authors: [], at: new Date().toISOString() }, cloud);+ assert.equal(existsSync(join(process.env.TRAIL_HOME!, "outbox.jsonl")), false);+ assert.deepEqual(cloudLines(me, { command: "ask", agent: true }), []);+ assert.equal(listNotes(me).length, 1);+ // The same connection made by `trail login` keeps today's behaviour.+ const { via: _via, ...byLogin } = cloud;+ assert.equal(inWorkspace(me, byLogin), true);+});