Skip to content

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

feat(brain): get a repo its brain from the terminal, via a loopback handoff

anirudhkumar-nanonets398b5c6ad304
diff --git a/src/brain/signup.ts b/src/brain/signup.ts
new file mode 100644
index 00000000..db2740f5
--- /dev/null
+++ b/src/brain/signup.ts
@@ -0,0 +1,183 @@
+/**
+ * Getting a brain without leaving the terminal.
+ *
+ * Until now a brain could only begin in the browser. You signed up on Trail, it
+ * created the brain, and handed you a `graft init --brain <id>:<token>` line to
+ * paste. That is the right way round when the website is where you already are,
+ * and the wrong way round when you are standing in a repository with graft
+ * already installed — which is where most people meet graft first.
+ *
+ * So `graft brain push` on an unlinked repo starts here instead of stopping.
+ * Graft opens a listener on loopback, sends the browser to Trail carrying the
+ * repository it is standing in and the port to answer on, and waits. Trail does
+ * the signing up, makes a brain for that repository, and redirects back to the
+ * listener with the brain id and its read token. The push then carries on as if
+ * the repo had been linked all along.
+ *
+ * Two things keep that safe. The listener binds to 127.0.0.1, so nothing off
+ * this machine can reach it. And it accepts only a handoff echoing the random
+ * state it just generated, so some other page the user happens to have open
+ * cannot push a brain of its own choosing into their repository.
+ */
+import { spawn } from "node:child_process";
+import { createServer, type Server } from "node:http";
+import { randomBytes, timingSafeEqual } from "node:crypto";
+import type { AddressInfo } from "node:net";
+import type { BrainLink } from "./link.js";
+
+/** Default web host. Overridden by GRAFT_BRAIN_URL, for staging and self-hosted. */
+const DEFAULT_WEB_BASE_URL = "https://agents.nanonets.com";
+
+/** How long the listener waits for the browser before giving up. A signup can
+ * involve reading an email, so this is minutes rather than seconds. */
+export const HANDOFF_TIMEOUT_MS = 5 * 60 * 1000;
+
+/** The one path the listener answers on. */
+export const CALLBACK_PATH = "/graft/callback";
+
+/** What the browser sends back, or why it could not be accepted. */
+export type HandoffResult = { link: BrainLink } | { error: string };
+
+export interface Handoff {
+ /** The loopback port Trail must redirect to. */
+ port: number;
+ /** The nonce Trail must echo back. */
+ state: string;
+ /** Resolves once the browser answers, or when `timeoutMs` passes. */
+ wait(timeoutMs?: number): Promise<HandoffResult>;
+ /** Stop listening. Safe to call more than once. */
+ close(): void;
+}
+
+/** Constant-time compare of two states, length included. */
+function sameState(got: string, want: string): boolean {
+ const a = Buffer.from(got);
+ const b = Buffer.from(want);
+ if (a.length !== b.length) return false;
+ return timingSafeEqual(a, b);
+}
+
+/** The page the user is left looking at. Deliberately plain: it exists to say
+ * "go back to your terminal", and it is served from a throwaway port that is
+ * about to close, so there is nothing to style around. */
+function donePage(ok: boolean): string {
+ const msg = ok
+ ? "Your brain is connected. Return to your terminal — the push is already running."
+ : "That handoff did not match this terminal. Run `graft brain push` again.";
+ return `<!doctype html><meta charset="utf-8"><title>graft</title><body style="font:15px/1.5 system-ui,sans-serif;margin:3rem auto;max-width:32rem;color:#1F2129"><p>${msg}</p><p style="color:#676767">You can close this tab.</p>`;
+}
+
+/**
+ * Start listening for the browser's handoff.
+ *
+ * Port 0 so the OS picks a free one: a fixed port would collide with whatever
+ * else the developer is running, and a second graft in another terminal.
+ */
+export async function startHandoff(): Promise<Handoff> {
+ const state = randomBytes(24).toString("base64url");
+
+ let settle: (r: HandoffResult) => void = () => {};
+ const answered = new Promise<HandoffResult>((resolve) => {
+ settle = resolve;
+ });
+
+ const server: Server = createServer((req, res) => {
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
+ if (url.pathname !== CALLBACK_PATH) {
+ res.writeHead(404, { "content-type": "text/plain" });
+ res.end("not found");
+ return;
+ }
+
+ // Checked before anything is read out of the query, so a mismatched handoff
+ // never reaches the link-writing path at all.
+ if (!sameState(url.searchParams.get("state") ?? "", state)) {
+ res.writeHead(400, { "content-type": "text/html; charset=utf-8" });
+ res.end(donePage(false));
+ return;
+ }
+
+ const brainId = (url.searchParams.get("brain") ?? "").trim();
+ const token = (url.searchParams.get("token") ?? "").trim();
+ if (!brainId || !token) {
+ res.writeHead(400, { "content-type": "text/html; charset=utf-8" });
+ res.end(donePage(false));
+ settle({ error: "the browser came back without a brain id and token" });
+ return;
+ }
+
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
+ res.end(donePage(true));
+ // No `baseUrl` stored, matching `connect`: GRAFT_BRAIN_URL is read again on
+ // every use, so persisting it here would only freeze a host that the env
+ // var is already free to move.
+ settle({ link: { brainId, token } });
+ });
+
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", () => {
+ server.removeAllListeners("error");
+ resolve();
+ });
+ });
+
+ const port = (server.address() as AddressInfo).port;
+ let closed = false;
+ const close = () => {
+ if (closed) return;
+ closed = true;
+ server.close();
+ };
+
+ return {
+ port,
+ state,
+ close,
+ async wait(timeoutMs = HANDOFF_TIMEOUT_MS): Promise<HandoffResult> {
+ let timer: NodeJS.Timeout | undefined;
+ const timeout = new Promise<HandoffResult>((resolve) => {
+ timer = setTimeout(
+ () => resolve({ error: "timed out waiting for the browser — run `graft brain push` again, or use the link above" }),
+ timeoutMs,
+ );
+ // The timer must not hold the process open once the browser has answered.
+ timer.unref?.();
+ });
+ try {
+ return await Promise.race([answered, timeout]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ close();
+ }
+ },
+ };
+}
+
+/** Where to send the browser for a repo's brain. */
+export function signupUrl(opts: { repo: string; port: number; state: string; baseUrl?: string }): string {
+ const base = (process.env.GRAFT_BRAIN_URL || opts.baseUrl || DEFAULT_WEB_BASE_URL).replace(/\/+$/, "");
+ const q = new URLSearchParams({
+ step: "repo",
+ graft_repo: opts.repo,
+ graft_port: String(opts.port),
+ graft_state: opts.state,
+ });
+ return `${base}/get-started?${q.toString()}`;
+}
+
+/** Open the user's browser, best effort. A machine with no opener is not an
+ * error: the URL is printed too, and that is the fallback everywhere.
+ *
+ * GRAFT_NO_BROWSER leaves the printed URL as the only route, which is what a
+ * test wants, and what someone on a machine whose `open` does something
+ * surprising wants too. */
+export function openBrowser(url: string): void {
+ if (process.env.GRAFT_NO_BROWSER) return;
+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
+ try {
+ spawn(opener, [url], { stdio: "ignore", detached: true, shell: process.platform === "win32" }).unref();
+ } catch {
+ /* the printed URL is the fallback */
+ }
+}
diff --git a/src/cli.ts b/src/cli.ts
index 66be92fd..cc62fdb3 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -21,7 +21,8 @@ import { parseBrainArg, connectBrain, pullBrain, brainStatus } from "./brain/con
import { rulesForPointers } from "./brain/attach.js";
import { clearLink, type BrainLink } from "./brain/link.js";
import { buildLocalDigest, fetchExpectedRepo, pushDigest, repoSlugFromGit, sameRepo } from "./brain/push.js";
-import { readLink } from "./brain/link.js";
+import { readLink, writeLink } from "./brain/link.js";
+import { openBrowser, signupUrl, startHandoff } from "./brain/signup.js";
import { contextDirFor } from "./context/node-file.js";
import { loadGraphCached } from "./graph/load.js";
import { ensureFreshChildren, ensureFreshGraph, refreshNote } from "./graph/refresh.js";
@@ -1239,6 +1240,45 @@ const brain = program
.command("brain")
.description("The Trail brain attached to this repo: the rules mined from its own history");
+/**
+ * Get this repo a brain from the terminal, by sending the user through signup
+ * in their browser and catching the handoff on loopback.
+ *
+ * Returns the link, already saved, or null when the user should be left alone —
+ * every failure prints its own reason first, because the caller only needs to
+ * know whether to carry on.
+ */
+async function signUpForBrain(repo: string, slug: string): Promise<BrainLink | null> {
+ const handoff = await startHandoff();
+ const url = signupUrl({ repo: slug, port: handoff.port, state: handoff.state });
+
+ // Printed before the browser opens, and printed whether or not it opens: on a
+ // remote shell nothing can open, and on a desktop the window sometimes lands
+ // behind the terminal. The URL is the thing that always works.
+ console.error(`· ${slug} has no brain yet. Opening your browser to make one:`);
+ console.error(` ${url}`);
+
+ // A non-interactive shell has nobody to click anything, so waiting five
+ // minutes for a browser that will never come is worse than saying so now.
+ if (!process.stderr.isTTY) {
+ console.error("· not a terminal — open that link, then run `graft brain connect <brainId>:<token>` here");
+ handoff.close();
+ return null;
+ }
+
+ openBrowser(url);
+ console.error("· waiting for you to finish signing up…");
+
+ const got = await handoff.wait();
+ if ("error" in got) {
+ console.error(`✗ ${got.error}`);
+ return null;
+ }
+ writeLink(repo, got.link);
+ console.error(`✓ brain connected to ${slug}`);
+ return got.link;
+}
+
brain
.command("connect")
.description("Attach a brain to this repo and pull its rules")
@@ -1296,17 +1336,29 @@ brain
.option("--no-approve", "leave the mined rules as drafts for review")
.action(async (dir: string, opts: { approve?: boolean }) => {
const repo = resolve(dir);
- const link = readLink(repo);
+ // Resolved before the link, because an unlinked repo now signs up for a
+ // brain and Trail creates that brain FOR a named repository. Without a slug
+ // there is nothing to name it after — and the digest builder would fail on
+ // the same missing remote a moment later regardless.
+ const here = repoSlugFromGit(repo);
+ let link = readLink(repo);
if (!link) {
- console.error("· no brain attached — run `graft brain connect <brainId>:<token>` first");
- process.exitCode = 1;
- return;
+ if (!here) {
+ console.error("✗ this directory has no GitHub `origin` remote — graft can only push a GitHub repository today");
+ process.exitCode = 1;
+ return;
+ }
+ const signedUp = await signUpForBrain(repo, `${here.owner}/${here.name}`);
+ if (!signedUp) {
+ process.exitCode = 1;
+ return;
+ }
+ link = signedUp;
}
// What the website said this brain is for. Checked BEFORE any reading, so
// standing in the wrong checkout costs a message rather than a brain full
// of another repository's rules — a mistake that is silent afterwards,
// because the rules look perfectly plausible, just not about your code.
- const here = repoSlugFromGit(repo);
const expected = await fetchExpectedRepo(link);
if (expected && here && !sameRepo(expected.slug, `${here.owner}/${here.name}`)) {
console.error(`✗ this brain is for ${expected.slug}, but you are in ${here.owner}/${here.name}`);
diff --git a/test/brain-signup.test.ts b/test/brain-signup.test.ts
new file mode 100644
index 00000000..a4be8169
--- /dev/null
+++ b/test/brain-signup.test.ts
@@ -0,0 +1,90 @@
+/**
+ * The terminal half of signing up for a brain.
+ *
+ * Two of these are security-relevant rather than merely correct. The listener
+ * must refuse a handoff that does not echo the state it generated, because it
+ * is an open port on the developer's machine and any page they have open can
+ * reach loopback. And it must bind to loopback only, so the handoff is not
+ * offered to the network the laptop is sitting on.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { CALLBACK_PATH, signupUrl, startHandoff } from "../src/brain/signup.js";
+
+/** Drive the callback the way the browser would. */
+async function callback(port: number, q: Record<string, string>): Promise<number> {
+ const url = `http://127.0.0.1:${port}${CALLBACK_PATH}?${new URLSearchParams(q).toString()}`;
+ const res = await fetch(url);
+ await res.text();
+ return res.status;
+}
+
+test("handoff: the browser's answer becomes the link", async () => {
+ const h = await startHandoff();
+ const waiting = h.wait(5000);
+
+ const status = await callback(h.port, { state: h.state, brain: "brain-123", token: "gbt_1.abc" });
+ assert.equal(status, 200);
+
+ const got = await waiting;
+ assert.deepEqual(got, { link: { brainId: "brain-123", token: "gbt_1.abc" } });
+});
+
+test("handoff: a wrong state is refused and never settles the wait", async () => {
+ const h = await startHandoff();
+ const waiting = h.wait(300);
+
+ const status = await callback(h.port, { state: "not-the-state", brain: "brain-123", token: "gbt_1.abc" });
+ assert.equal(status, 400, "a mismatched state is rejected outright");
+
+ const got = await waiting;
+ assert.ok("error" in got, "the push must not proceed on a handoff it did not ask for");
+});
+
+test("handoff: the right state without a brain and token is an error, not a link", async () => {
+ const h = await startHandoff();
+ const waiting = h.wait(5000);
+
+ const status = await callback(h.port, { state: h.state, brain: "", token: "" });
+ assert.equal(status, 400);
+
+ const got = await waiting;
+ assert.ok("error" in got);
+});
+
+test("handoff: anything but the callback path is a 404", async () => {
+ const h = await startHandoff();
+ const res = await fetch(`http://127.0.0.1:${h.port}/`);
+ await res.text();
+ assert.equal(res.status, 404);
+ h.close();
+});
+
+test("handoff: the wait gives up rather than hanging forever", async () => {
+ const h = await startHandoff();
+ const got = await h.wait(150);
+ assert.ok("error" in got);
+ assert.match((got as { error: string }).error, /timed out/);
+});
+
+test("signup url: carries the repo, the port and the state", () => {
+ const url = new URL(signupUrl({ repo: "NanoNets/Graft", port: 51234, state: "s-t-a-t-e" }));
+ assert.equal(url.origin, "https://agents.nanonets.com");
+ assert.equal(url.pathname, "/get-started");
+ assert.equal(url.searchParams.get("graft_repo"), "NanoNets/Graft");
+ assert.equal(url.searchParams.get("graft_port"), "51234");
+ assert.equal(url.searchParams.get("graft_state"), "s-t-a-t-e");
+ assert.equal(url.searchParams.get("step"), "repo");
+});
+
+test("signup url: GRAFT_BRAIN_URL points signup at staging too", () => {
+ const before = process.env.GRAFT_BRAIN_URL;
+ process.env.GRAFT_BRAIN_URL = "https://staging-agents.nanonets.com/";
+ try {
+ const url = new URL(signupUrl({ repo: "a/b", port: 1, state: "s" }));
+ assert.equal(url.origin, "https://staging-agents.nanonets.com", "a trailing slash must not double up");
+ } finally {
+ if (before === undefined) delete process.env.GRAFT_BRAIN_URL;
+ else process.env.GRAFT_BRAIN_URL = before;
+ }
+});