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
fix(trail): init --connect says it's offline once with the --server to retry, and measures product code
Rushabh Nagda1f7cebeab1f2
diff --git a/src/cli.ts b/src/cli.tsindex a1fffa6d..bac6a570 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -67,6 +67,8 @@ import { clearPending, cloudLines, loginLink, sessionKey, waitForConnect } fromimport { addRepo, clearCloud, cloudEnabled, fetchMe, fetchTeam, isError, readCloud, trailUrl, writeCloud, type Cloud } from "./cloud/workspace.js";import {claimConnectCode,+ connectAgain,+ offlineLine,learningsSummary,machineName,normalizeCode,@@ -1823,7 +1825,7 @@ async function runConnectInit(dir: string, opts: InitOptions): Promise<void> {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`);+ console.error(offlineLine(got.error, base, code, cmd("graft init")));}const reporter = cloud ? new OnboardingReporter(cloud, ref, { machine }) : null;void reporter?.stage("connected");@@ -1870,7 +1872,7 @@ async function runConnectInit(dir: string, opts: InitOptions): Promise<void> {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`);+ console.error(`· couldn't send the summary to Trail this time · with a new code from ${base}/welcome/code, ${connectAgain(cmd("graft init"), "<code>", base)} sends it again`);}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`);diff --git a/src/cloud/onboarding.ts b/src/cloud/onboarding.tsindex 8c70fadf..dce735c8 100644--- a/src/cloud/onboarding.ts+++ b/src/cloud/onboarding.ts@@ -30,7 +30,7 @@ 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";+import { DEFAULT_TRAIL_URL, isError, trailUrl, type ApiError, type Cloud } from "./workspace.js";type Fetch = typeof fetch;@@ -142,14 +142,15 @@ export async function claimConnectCode(): 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 === undefined) return { error: r.error, reason: "offline" };+ if (r.status >= 500) return { error: `Trail answered ${r.status}`, 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" };+ if (!b?.token || !ws?.name) return { error: "Trail sent an answer with no workspace in it", reason: "offline" };const id = ws.id ?? ws.slug ?? ws.name;return {cloud: {@@ -171,6 +172,26 @@ export async function claimConnectCode(};}+/**+ * The command that connects later: `trail init --connect TRL-… --server <url>`,+ * naming the Trail it was run against unless that's Trail cloud, so it+ * reaches the same backend the code came from.+ */+export function connectAgain(command: string, code: string, base: string): string {+ return `${command} --connect ${code}${base.replace(/\/+$/, "") === DEFAULT_TRAIL_URL ? "" : ` --server ${base}`}`;+}++/**+ * What to say, once, when Trail didn't take the code because it couldn't be+ * reached: which Trail, what happened, and the exact command to connect later.+ * `· couldn't reach Trail at http://localhost:5173 · set this repo up anyway ·+ * to connect it later: trail init --connect TRL-7F2A-K9QD --server http://localhost:5173`+ */+export function offlineLine(error: string, base: string, code: string, command: string): string {+ const what = error.startsWith("Trail ") ? `Trail at ${base}${error.slice("Trail".length)}` : `couldn't reach Trail at ${base}`;+ return `· ${what} · set this repo up anyway · to connect it later: ${connectAgain(command, code, base)}`;+}+/* -------------------------------------------------------------------------- *//* the stages and the summary *//* -------------------------------------------------------------------------- */@@ -280,9 +301,21 @@ export function parseAskSavings(text: string): Omit<TokensSummary, "question" |return { saved: n(m[1]!), pct: n(m[2]!), pack: n(m[3]!), files: n(m[4]!), baseline: n(m[5]!) };}+/** Folders that hold tests, fixtures, vendored or generated code, anywhere in a path. */+const NOT_PRODUCT_DIR = /(^|\/)(test|tests|__tests__|testdata|test-fixtures|fixtures|__fixtures__|__mocks__|vendor|third_party|node_modules|generated|__generated__|gen)\//i;+/** File names of tests and generated code: `client_test.go`, `a.test.ts`, `a.spec.js`, `test_client.py`, `api.pb.go`, `schema.generated.ts`. */+const NOT_PRODUCT_FILE = /(_test\.[^/]+|\.(test|spec)\.[^/]+|_spec\.[^/]+|(^|\/)test_[^/]+\.py|(^|\/)conftest\.py|\.(generated|gen)\.[^/]+|\.pb\.go|_pb2(_grpc)?\.py|\.d\.ts)$/i;++/** Whether a repo path is test, fixture, vendored or generated code, which a lookup shouldn't be measured on. */+export function notProductCode(path: string): boolean {+ const p = path.split("\\").join("/");+ return NOT_PRODUCT_DIR.test(p) || NOT_PRODUCT_FILE.test(p);+}+/*** 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+ * about the repo's most central symbol (most incoming edges) outside tests,+ * fixtures, vendored and generated code, 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.@@ -291,7 +324,11 @@ export function tokensOnOneLookup(repo: string, opts: { contextDir?: string; tritry {const graph = loadGraphCached(contextDirFor(repo, opts.contextDir));if (!graph) return null;- const hubs = buildRepoMap(graph, { hotspots: Math.max(1, opts.tries ?? 5) }).hotspots;+ // The most central symbols of the product code: tests, fixtures, vendored+ // and generated code only when there's nothing else.+ const all = buildRepoMap(graph, { hotspots: 500 }).hotspots;+ const product = all.filter((h) => !notProductCode(h.path));+ const hubs = (product.length ? product : all).slice(0, Math.max(1, opts.tries ?? 5));for (const hub of hubs) {const query = `how does ${hub.name} work`;const r = ask(repo, query, { source: true, limit: 5, contextDir: opts.contextDir });diff --git a/src/cloud/workspace.ts b/src/cloud/workspace.tsindex 5348695a..dcfd34c1 100644--- a/src/cloud/workspace.ts+++ b/src/cloud/workspace.ts@@ -18,7 +18,7 @@ import { trailHome } from "../notes/home.js";import { readJson, writeJsonAtomic } from "../util/state.js";/** Trail's own front end and API. TRAIL_URL (or the older GRAFT_BRAIN_URL) moves it, for a local or self-hosted Trail. */-const DEFAULT_TRAIL_URL = "https://app.trailhq.com";+export const DEFAULT_TRAIL_URL = "https://app.trailhq.com";export function trailUrl(env: NodeJS.ProcessEnv = process.env): string {return (env.TRAIL_URL || env.GRAFT_BRAIN_URL || DEFAULT_TRAIL_URL).replace(/\/+$/, "");diff --git a/test/trail-connect-cli.test.ts b/test/trail-connect-cli.test.tsindex 3539da88..f92abe89 100644--- a/test/trail-connect-cli.test.ts+++ b/test/trail-connect-cli.test.ts@@ -186,9 +186,20 @@ test("offline, init still sets the repo up and says how to connect later", asyncconst 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/);+ // Said once, naming the Trail it tried, with the exact command that reaches it again.+ const said = r.stderr.split("\n").filter((l) => /reach Trail|Trail at /.test(l));+ assert.deepEqual(said, [+ "· couldn't reach Trail at http://127.0.0.1:9 · set this repo up anyway · to connect it later: trail init --connect TRL-GOOD-C0DE --server http://127.0.0.1:9",+ ]);+ assert.equal((r.stderr.match(/couldn't reach Trail/g) ?? []).length, 1);assert.ok(existsSync(join(repo, ".claude", "settings.json")));assert.equal(existsSync(join(env.TRAIL_HOME!, "cloud.json")), false);++ // The same with --server: the hint carries the --server that was used.+ const flagged = await run(["init", repo, "--connect", GOOD_CODE, "--server", "http://127.0.0.1:9/", "--agents", "claude", "--no-global", "--no-build"], { ...env, TRAIL_URL: "" });+ assert.equal(flagged.status, 0, flagged.stderr);+ assert.equal((flagged.stderr.match(/couldn't reach Trail/g) ?? []).length, 1);+ assert.match(flagged.stderr, /to connect it later: trail init --connect TRL-GOOD-C0DE --server http:\/\/127\.0\.0\.1:9$/m);});test("without --connect, init sends nothing anywhere and prints what it always did", async () => {diff --git a/test/trail-connect.test.ts b/test/trail-connect.test.tsindex e28c32da..fb0ff88f 100644--- a/test/trail-connect.test.ts+++ b/test/trail-connect.test.ts@@ -16,6 +16,9 @@ import { buildGraph } from "../src/graph/build.js";import {claimConnectCode,conflictLine,+ connectAgain,+ notProductCode,+ offlineLine,learningTerms,learningsSummary,normalizeCode,@@ -204,6 +207,57 @@ test("one real lookup on the fresh map: the most central symbol, and what readinassert.equal(tokensOnOneLookup(mkdtempSync(join(tmpdir(), "connect-nograph-"))), null);});+test("tests, fixtures, vendored and generated code are not product code", () => {+ for (const p of [+ "client_test.go", "pkg/retry/client_test.go", "src/a.test.ts", "src/a.spec.js", "lib/a_spec.rb", "tests/test_client.py", "test_client.py",+ "test/helpers.ts", "tests/util.py", "src/__tests__/x.tsx", "testdata/in.go", "fixtures/repo.ts", "spec/fixtures/a.rb",+ "vendor/github.com/x/y.go", "third_party/z.c", "generated/api.ts", "src/__generated__/schema.ts", "api/v1/api.pb.go",+ "proto/api_pb2.py", "src/schema.generated.ts", "src\\__tests__\\win.ts",+ ])+ assert.ok(notProductCode(p), p);+ for (const p of ["client.go", "src/cli.ts", "src/testing.ts", "src/latest.ts", "contest/score.py", "src/generator.ts", "attest/x.go", "src/test-utils-free.ts"])+ assert.ok(!notProductCode(p), p);+});++test("the lookup is about product code: a test helper everyone calls is passed over, unless tests are all there is", async () => {+ const dir = mkdtempSync(join(tmpdir(), "connect-tokens-tests-"));+ 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(dir, "client.ts"), `export function retryDo(attempts: number): number {\n return attempts;\n}\n\n${filler}`);+ writeFileSync(join(dir, "a.ts"), 'import { retryDo } from "./client";\nexport function useA() {\n return retryDo(4);\n}\n');+ mkdirSync(join(dir, "test"));+ // tmpRepo has more callers than anything in the product code.+ writeFileSync(join(dir, "test", "helpers.ts"), `export function tmpRepo(name: string): string {\n return name;\n}\n\n${filler}`);+ for (const f of ["a", "b", "c", "d", "e", "f", "g", "h"])+ writeFileSync(join(dir, "test", `${f}.test.ts`), `import { tmpRepo } from "./helpers";\nexport function t${f}() {\n return tmpRepo("x");\n}\n`);+ await buildGraph(dir);+ const { buildRepoMap } = await import("../src/graph/map.js");+ const { loadGraphCached } = await import("../src/graph/load.js");+ const { contextDirFor } = await import("../src/context/node-file.js");+ assert.equal(buildRepoMap(loadGraphCached(contextDirFor(dir))!).hotspots[0]!.name, "tmpRepo", "the test helper is the most central symbol");+ const t = tokensOnOneLookup(dir);+ assert.ok(t);+ assert.equal(t.symbol, "retryDo");+ assert.equal(t.question, "how retryDo works");++ const onlyTests = mkdtempSync(join(tmpdir(), "connect-tokens-onlytests-"));+ mkdirSync(join(onlyTests, "test"));+ writeFileSync(join(onlyTests, "test", "helpers.ts"), `export function tmpRepo(name: string): string {\n return name;\n}\n\n${filler}`);+ for (const f of ["a", "b", "c"]) writeFileSync(join(onlyTests, "test", `${f}.test.ts`), `import { tmpRepo } from "./helpers";\nexport function t${f}() {\n return tmpRepo("x");\n}\n`);+ await buildGraph(onlyTests);+ assert.equal(tokensOnOneLookup(onlyTests)?.symbol, "tmpRepo", "nothing else to measure: a test helper it is");+});++test("the offline line names the Trail it tried once, and the command to connect later carries --server unless it's Trail cloud", () => {+ assert.equal(connectAgain("trail init", "TRL-7F2A-K9QD", "https://app.trailhq.com"), "trail init --connect TRL-7F2A-K9QD");+ assert.equal(connectAgain("trail init", "TRL-7F2A-K9QD", "https://dev.trailhq.com"), "trail init --connect TRL-7F2A-K9QD --server https://dev.trailhq.com");+ assert.equal(+ offlineLine("couldn't reach Trail", "http://localhost:5173", "TRL-7F2A-K9QD", "trail init"),+ "· couldn't reach Trail at http://localhost:5173 · set this repo up anyway · to connect it later: trail init --connect TRL-7F2A-K9QD --server http://localhost:5173",+ );+ assert.match(offlineLine("Trail didn't answer in time", "https://dev.trailhq.com", "TRL-7F2A-K9QD", "trail init"), /^· Trail at https:\/\/dev\.trailhq\.com didn't answer in time · /);+ assert.match(offlineLine("Trail answered 502", "https://app.trailhq.com", "TRL-7F2A-K9QD", "trail init"), /^· Trail at https:\/\/app\.trailhq\.com answered 502 · set this repo up anyway · to connect it later: trail init --connect TRL-7F2A-K9QD$/);+});+/* learnings ---------------------------------------------------------------- */test("a learning goes up as its title, one short line and its session count: no code block, no provenance line", () => {