Skip to content

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

Remove graft trail push/pull and the brain client

anirudhkumar-nanonetsb92c22e8f604
diff --git a/README.md b/README.md
index 4082f989..cf75b0fe 100644
--- a/README.md
+++ b/README.md
@@ -359,7 +359,6 @@ Where a CLI agent supports user-level `hooks.json`, `init` also installs Graft's
- **a live statusline** — graph size, % enriched, and a `⚠ N stale` warning when the code has moved ahead of the graph
- **auto-sync** — every graft query brings the graph up to date first, so an answer always describes the code as it is right now, uncommitted edits included. A query refreshes only what it reads; the markdown under `graft/` is refreshed by the background rebuild at the end of a turn that touched code. Both are structural and `$0` — auto-sync never calls the LLM on its own
- **context on tap** — each prompt pulls the matching nodes into the session; editing a file surfaces what depends on it ("blast radius"); new sessions start with the repo map
-- **a trail that keeps up** — in a repo with a Trail attached, a new session is told when accepted changes are waiting for `graft trail pull` or suggestions are waiting for review (one check, capped at 3 s). At most once a day, and only when HEAD has moved since the last push, it also starts a background `graft trail push --no-watch` so the suggestions follow the history (its output goes to `.graft/trail-push.log`). Turn that off with `GRAFT_TRAIL_AUTOPUSH=0`, or `"trailAutoPush": false` in `.graft/config.json`
<p align="center">
<img src="assets/graft-hooks-demo.gif" alt="How Claude Code hooks wire graft in: install, graft init, then the hooks loop (session start, user prompt, post tool use, stop) keeps the graph built, read, and committed automatically" width="820"/>
@@ -420,13 +419,6 @@ graft check --json # print the drift report as JSON
# GRAFT_NO_REFRESH=1 # same, for every command
# GRAFT_REFRESH=hash # hash every file instead of trusting size+mtime
-graft trail push [dir] # read this repo's history into its Trail (the first run signs up in the browser)
-graft trail pull [dir] # write the changes accepted in Trail into CLAUDE.md, AGENTS.md and the other context files
-graft trail pull --dry-run # what would be written, and how many suggestions are waiting for review
-graft trail watch [dir] # wait until Trail has suggestions to review or accepted changes to pull, then say so once
-graft trail watch --accepted-only # keep waiting through suggestions; stop only on accepted changes
-graft trail watch --json # the same ending, machine-readable (exit 0: something to act on, 2: timed out)
-
graft viz [dir] # see the graph: serves an interactive viewer on localhost
graft viz --port 5000 --no-open # pick a port; don't auto-open the browser
graft viz --export site/ --title "PR #12" # one self-contained index.html — for CI, GitHub Pages, or a build artifact
diff --git a/TELEMETRY.md b/TELEMETRY.md
index a913c6fb..bf9d8b19 100644
--- a/TELEMETRY.md
+++ b/TELEMETRY.md
@@ -47,11 +47,8 @@ The events:
| `build_completed` | `files_bucket`, `langs`, `mode` (`fast`/`deep`), `duration_bucket`, `incremental` | A build succeeds |
| `build_failed` | `stage`, `code` — both fixed enums | A build throws |
| `query` | `command`, `surface` (`cli`/`mcp`/`hook`), `hit` (`ask` only), `notes` (`0`/`1`/`2`, how many session notes `ask` showed; only in a repo that keeps notes) | Any query command |
-| `brain_signup_opened` | `mode` (`terminal`/`agent`/`nudge`), and for a nudge `command` (`ask`/`note`/`check`) and `wording` (`share`/`learned`) | `graft trail push` on a repo with no brain opens your browser to make one, or a trail command hands the agent a sign-in link to pass on (at most once a session) |
+| `brain_signup_opened` | `mode` (`terminal`/`agent`/`nudge`), and for a nudge `command` (`ask`/`note`/`check`) and `wording` (`share`/`learned`) | A trail command hands the agent a sign-in link to pass on (at most once a session) |
| `brain_signup_settled` | `outcome` (`linked`/`timed_out`/`bad_callback`/`stopped`, and for an agent-run push `agent_link_opened`/`still_waiting`/`expired`/`unsupported`), `mode` (`terminal`/`agent`/`nudge`), `duration_bucket` | That handoff ends, one way or the other — for an agent-run push, each of its runs; for a nudge, each background wait for the sign-in (`linked`/`timed_out`/`expired`/`unsupported`) |
-| `trail_pulled` | `outcome` (`written`/`already_present`/`nothing_accepted`/`skipped`/`error`/`dry_run`), `kinds` (which kinds of context file were written: `claude_md`, `folder_claude_md`, `agents_md`, `cursor_rule`, `skill`), `files_bucket`, `changes_bucket`, `skipped_bucket`, `suggested_bucket` (every change Trail has suggested for the wired agents' files, whatever became of it) | `graft trail pull` (or `graft claude-md pull`) finishes |
-| `trail_watch_exit` | `reason` (`suggestions`/`accepted`/`timeout`/`refused`/`no_trail`), `suggested_bucket`, `accepted_bucket`, `duration_bucket` (how long it waited) | `graft trail watch` ends |
-| `trail_autopush` | `outcome` (`started`/`skipped`), `reason` when skipped (`disabled`/`no_head`/`head_unchanged`/`throttled`/`spawn_failed`) | A Claude Code or Codex session starts in a repo with a trail attached, and the hook decides whether to refresh it with a background `graft trail push`. Repos without a trail send nothing |
| `note_saved` | `has_cost` (`true`/`false`), `touches_bucket` (how many files the learning is about, bucketed), `scope` (`repo`/`personal`) | `trail note` saves a learning, in the repo's `.trail/` or on this machine. The title, the text and the paths are never sent |
| `learning_reused` | `teammate` (`true`/`false`), `saved_tokens_bucket` | `trail ask` shows learnings from earlier sessions. Which ones, and their text, are never sent |
| `repo_seen` | `trail_committed` (`true`/`false`), `learnings_bucket`, `workspace` (`true`/`false`) | Once a day per repo, when a Claude Code session starts in a repo trail runs in. The repo's name and paths are never sent; it's identified only by the random `repo_id` every event carries |
diff --git a/src/ask/ask.ts b/src/ask/ask.ts
index 3416f886..56196542 100644
--- a/src/ask/ask.ts
+++ b/src/ask/ask.ts
@@ -48,8 +48,6 @@ import {
} from "./graphrank.js";
import { readSourceFile } from "../util/source.js";
import { counts, tokenize, type AskIndex, type AskIndexDoc } from "./index-file.js";
-import { rulesForPointers, formatRules, type AppliedRule } from "../brain/attach.js";
-import { readLink, readRulesCache } from "../brain/link.js";
import { cmd, tag } from "../brand.js";
import { formatNoteHits, learningSavingsLine, type NoteHit } from "../notes/notes.js";
@@ -146,11 +144,6 @@ export interface AskResult {
scopes?: { federated: string[]; alsoMatched: { scope: string; bestId: string }[] };
/** @internal Opt-in latent file groups plus the exact pre-file-ranking list. */
ranking?: AskRankingMetadata;
- /** Rules from the attached Trail brain that govern the symbols in `hits`.
- * Absent when the repo has no brain linked, or when none of its rules touch
- * this answer. Populated in `--source` mode only, alongside `saved`: a pack
- * the agent does not read the code from has nothing for a rule to sit beside. */
- rules?: AppliedRule[];
}
/** First real prose line of a node body (skips headings, markers, blanks). */
@@ -1403,29 +1396,10 @@ export function ask(dir: string, query: string, opts: AskOptions = {}): AskResul
// The pack is truly substitutive only in retriever mode (spans inlined), so
// the "vs reading whole files" estimate is only honest here.
result.saved = baselineFor(result.hits, corpus.graph);
- // What the team decided about the code this pack just inlined. Read from the
- // local cache only — `ask` is on the agent's hot path and must never wait on
- // the network; `graft trail pull` and `init` are what refresh it.
- const applied = attachBrainRules(root, result.hits, corpus.graph);
- if (applied.length) result.rules = applied;
}
return result;
}
-/** Rules for this answer's symbols, or [] when the repo has no brain linked,
- * the cache is missing, or nothing overlaps. Never throws: a broken link must
- * degrade to the code-only answer graft gave before a brain existed. */
-function attachBrainRules(root: string, hits: AskHit[], graph: GraphV1 | null): AppliedRule[] {
- try {
- if (!readLink(root)) return [];
- const cache = readRulesCache(root);
- if (!cache?.rules?.length) return [];
- return rulesForPointers(hits.map((h) => h.pointer), cache.rules, graph);
- } catch {
- return [];
- }
-}
-
// ── Skeleton view ────────────────────────────────────────────────────────────
export interface SkeletonEntry {
@@ -1551,9 +1525,6 @@ export function formatAsk(r: AskResult): string {
});
lines.push(...scopeFooterLines(r));
}
- // Before `body` is joined, so the rules text is counted in the savings line
- // below rather than claimed as free.
- if (r.rules?.length) lines.push(...formatRules(r.rules));
const body = lines.join("\n").trimEnd();
const savings = askSavingsLine(r, body);
return (savings ? `${savings}\n\n${body}` : body) + escalationNudge(r) + "\n";
diff --git a/src/brain/attach.ts b/src/brain/attach.ts
deleted file mode 100644
index 479008ae..00000000
--- a/src/brain/attach.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * Attach a brain's rules to an `ask` answer.
- *
- * The join is the symbol: a rule is mined against a graft node id, and an
- * answer is a set of hits that point at spans. Resolving the hits back to node
- * ids gives the rules that govern exactly what the agent is about to read.
- *
- * Staleness is decided HERE, on the machine that has the code: the rule carries
- * the symbol's body hash from when it was mined, and the local graph carries
- * the hash now. A mismatch means the code moved out from under the rule, which
- * is worth saying rather than hiding — a rule that describes code that no
- * longer exists is the failure mode this whole mechanism exists to catch.
- */
-import type { GraphV1 } from '../graph/types.js';
-import type { BrainRule } from './link.js';
-
-/** One rule, resolved against the current graph. */
-export interface AppliedRule {
- rule: string;
- /** The symbol it governs, as a `path:span` pointer the agent can open. */
- pointer: string;
- /** True when the symbol's body hash no longer matches what the rule was mined at. */
- stale: boolean;
- sourceUrl?: string;
-}
-
-/** Most rules to attach to one answer. */
-export const MAX_ATTACHED_RULES = 6;
-
-/**
- * The rules governing the symbols in `pointers`, resolved against `graph`.
- *
- * Scoped to the answer, not the repo: attaching every rule a brain holds would
- * turn a token-saving pack into a token-spending one, and `ask` prints the
- * saving it claims. Capped for the same reason.
- */
-export function rulesForPointers(
- pointers: string[],
- rules: BrainRule[],
- graph: GraphV1 | null,
-): AppliedRule[] {
- if (!rules.length || !graph) return [];
-
- // node id → its current pointer and body hash. One pass over the graph; the
- // caller does this once per ask, not once per hit.
- const byId = new Map<string, { pointer: string; hash: string }>();
- for (const n of graph.nodes) {
- byId.set(n.id, { pointer: `${n.path}:${n.span}`, hash: n.body_hash });
- }
-
- const wanted = new Set(pointers);
- const out: AppliedRule[] = [];
- const seen = new Set<string>();
- for (const r of rules) {
- const node = byId.get(r.symbol);
- if (!node || !wanted.has(node.pointer)) continue;
- // The same rule can be mined against two symbols in one answer; show it once.
- if (seen.has(r.rule)) continue;
- seen.add(r.rule);
- out.push({
- rule: r.rule,
- pointer: node.pointer,
- // No recorded fingerprint means the rule was mined before hashing existed
- // (or against a symbol graft could not hash). Unknown is not stale: a
- // false "the code moved" is worse than saying nothing about freshness.
- stale: r.fingerprint !== '' && r.fingerprint !== node.hash,
- sourceUrl: r.sourceUrl,
- });
- if (out.length === MAX_ATTACHED_RULES) break;
- }
- return out;
-}
-
-/**
- * Render the rules block appended to an `ask` pack.
- *
- * Deliberately terse. This rides along on every answer, so it has to earn its
- * tokens: one line per rule, the pointer it governs, and a link only when there
- * is one. The `[graft]` prefix is avoided — `sumSavingsFooters` scans for
- * `[graft] tokens saved ≈` and nothing here should look like a savings line.
- */
-export function formatRules(applied: AppliedRule[]): string[] {
- if (!applied.length) return [];
- const lines = ['', 'rules that govern these symbols'];
- for (const a of applied) {
- const flag = a.stale ? ' (STALE — the code changed since this was decided)' : '';
- lines.push(`- ${a.rule}${flag}`);
- lines.push(` ${a.pointer}${a.sourceUrl ? ` · ${a.sourceUrl}` : ''}`);
- }
- return lines;
-}
diff --git a/src/brain/autopush.ts b/src/brain/autopush.ts
deleted file mode 100644
index 9891f0bb..00000000
--- a/src/brain/autopush.ts
+++ /dev/null
@@ -1,269 +0,0 @@
-/**
- * Keeping a trail current without anyone asking: a background `graft trail
- * push`, at most once a day, started by the session-start hook.
- *
- * A trail is read out of a repository's history, and its CLAUDE.md suggestions
- * are only as fresh as the last push. Nobody re-runs a push by hand — it is the
- * command you run once, during onboarding — so a trail attached in March was
- * still suggesting from March's history in September. The session-start hook is
- * the one place graft runs on its own every working day, so it is where the
- * refresh goes.
- *
- * Restraint is most of this file:
- *
- * - Only for a repo with a trail attached. The push's other path, for a repo
- * without one, signs up for a trail and opens a browser; a hook must never
- * get anywhere near that, so no link means nothing happens at all — and the
- * child is told it was started from here (AUTOPUSH_CHILD_ENV), so a link
- * that disappears in the moment between this check and the child starting
- * still cannot send it to sign-up.
- * - Only when HEAD has moved since the last push graft recorded, because a push
- * of the same history mines the same rules.
- * - At most once in 24 hours, stamped BEFORE the child starts, so a push that
- * fails, or ten sessions opened in one morning, cost one push and not ten.
- * - Fully detached: `--no-watch`, stdin closed, output to a log under
- * `.graft/`, unref'd. The session never waits on it.
- * - Off with GRAFT_TRAIL_AUTOPUSH=0, or `"trailAutoPush": false` in
- * `.graft/config.json`.
- *
- * The state lives in its own file beside the link rather than inside
- * `.graft/config.json`: the child writes it when its push lands, and a
- * read-modify-write of the file that holds the link, from a detached process,
- * racing whatever the foreground is doing, is how a token gets lost.
- */
-import { closeSync, openSync } from "node:fs";
-import { spawn, spawnSync } from "node:child_process";
-import { join } from "node:path";
-import { graftCliPath } from "../claude/paths.js";
-import { BUILD_CONFIG_DIR, readBuildConfig, readJson, writeJsonAtomic } from "../util/state.js";
-import { track } from "../telemetry/track.js";
-import type { TRAIL_AUTOPUSH_SKIPS } from "../telemetry/contract.js";
-import { readLink } from "./link.js";
-
-/** A day. The history a push reads moves by days, not minutes. */
-export const AUTOPUSH_INTERVAL_MS = 24 * 60 * 60 * 1000;
-
-/** Set on the background push's environment, so it can refuse the sign-up
- * path outright (see the push command in cli.ts). */
-export const AUTOPUSH_CHILD_ENV = "GRAFT_TRAIL_AUTOPUSH_CHILD";
-
-/** What graft remembers about this checkout's pushes. */
-export interface TrailPushState {
- /** HEAD when a push last reached Trail, from any push — by hand or in the background. */
- pushedHead?: string;
- pushedAt?: number;
- /** When a background push was last STARTED, and at which HEAD. Written before
- * the child is spawned, so a child that dies still throttles the next one. */
- autoPushAt?: number;
- autoPushHead?: string;
- /** Trail's suggestion count the last time the session-start hook read it —
- * what "new suggestions since your last session" is counted from (see
- * trailContextLine). Here rather than in config.json for the same reason as
- * the rest: the hook writes it on every session. */
- seenSuggested?: number;
-}
-
-export function trailPushStatePath(repo: string): string {
- return join(repo, BUILD_CONFIG_DIR, "trail-push.json");
-}
-
-/** Where the background push writes its output. Overwritten by each one, so it
- * never grows past a single push's worth. */
-export function trailPushLogPath(repo: string): string {
- return join(repo, BUILD_CONFIG_DIR, "trail-push.log");
-}
-
-export function readTrailPushState(repo: string): TrailPushState {
- return readJson<TrailPushState>(trailPushStatePath(repo)) ?? {};
-}
-
-function patchTrailPushState(repo: string, patch: TrailPushState): void {
- writeJsonAtomic(trailPushStatePath(repo), { ...readTrailPushState(repo), ...patch });
-}
-
-/**
- * Record a push that reached Trail. Called by `graft trail push` itself, by hand
- * or in the background, once the digest is accepted — so "HEAD has moved since
- * the last push" is judged against the last push that actually landed. Never
- * throws: failing to remember a push must not fail the push.
- */
-export function recordTrailPush(repo: string, head: string, now = Date.now()): void {
- if (!head || !linkStoredHere(repo)) return;
- try {
- patchTrailPushState(repo, { pushedHead: head, pushedAt: now });
- } catch {
- /* an unwritable .graft/ only means the next session may push once more */
- }
-}
-
-/**
- * Remember the suggestion count the session-start hook just read. Only for a
- * link saved here, like everything else in this file — for an env-only link
- * there is no git-ignored `.graft/` to keep it in, and such a checkout simply
- * hears about its suggestions every session. Never throws.
- */
-export function recordSeenSuggestions(repo: string, count: number): void {
- if (!linkStoredHere(repo)) return;
- try {
- if (readTrailPushState(repo).seenSuggested !== count) patchTrailPushState(repo, { seenSuggested: count });
- } catch {
- /* at worst the same suggestions are mentioned once more */
- }
-}
-
-/**
- * Whether the link is saved in this checkout's `.graft/config.json`, rather than
- * only supplied by GRAFT_BRAIN_TOKEN / GRAFT_BRAIN_ID.
- *
- * The saved link is what made `.graft/` git-ignored (see writeLink), so it is
- * also what makes it safe to leave state and a log beside it. A link from the
- * environment is how CI attaches a trail without writing to the checkout, and
- * a background push is no business of a CI checkout's either.
- */
-function linkStoredHere(repo: string): boolean {
- try {
- const b = readBuildConfig(repo)?.brain;
- return Boolean(b?.brainId && b?.token);
- } catch {
- return false;
- }
-}
-
-/** Why a background push did not start. `no_trail` is never reported — it is
- * every repo without a trail, on every session — so it is not an event. */
-export type AutopushSkip = "no_trail" | (typeof TRAIL_AUTOPUSH_SKIPS)[number];
-
-export type AutopushDecision = { start: true; head: string } | { start: false; reason: AutopushSkip };
-
-/** False when GRAFT_TRAIL_AUTOPUSH is `0`/`false`/`off`/`no`, or the repo's config says so. */
-export function autopushEnabled(repo: string, env: NodeJS.ProcessEnv = process.env): boolean {
- const v = (env.GRAFT_TRAIL_AUTOPUSH ?? "").trim().toLowerCase();
- if (["0", "false", "off", "no"].includes(v)) return false;
- try {
- return readBuildConfig(repo)?.trailAutoPush !== false;
- } catch {
- return true;
- }
-}
-
-/** HEAD's sha, or null when there is none (no git, no commits, a slow disk). */
-export function gitHead(repo: string): string | null {
- try {
- const r = spawnSync("git", ["rev-parse", "HEAD"], { cwd: repo, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 1500 });
- const out = typeof r.stdout === "string" ? r.stdout.trim() : "";
- return r.status === 0 && /^[0-9a-f]{7,64}$/.test(out) ? out : null;
- } catch {
- return null;
- }
-}
-
-/**
- * Whether to start a background push now. Pure but for what it is handed, so the
- * tests can walk every branch without git or a clock.
- *
- * A checkout with no push recorded at all counts as moved. Every trail attached
- * before this existed is in that state, and its last push is exactly as old as
- * the refresh exists to fix; the 24-hour stamp still holds it to one push.
- */
-export function decideAutopush(input: {
- linked: boolean;
- enabled: boolean;
- head: string | null;
- state: TrailPushState;
- now: number;
-}): AutopushDecision {
- if (!input.linked) return { start: false, reason: "no_trail" };
- if (!input.enabled) return { start: false, reason: "disabled" };
- if (!input.head) return { start: false, reason: "no_head" };
- const { state } = input;
- // Either push covers this HEAD: one that landed, or a background one already
- // started for it (which may still be running, or may have failed — in which
- // case the same history would fail the same way).
- if (input.head === state.pushedHead || input.head === state.autoPushHead) return { start: false, reason: "head_unchanged" };
- if (typeof state.autoPushAt === "number" && input.now - state.autoPushAt < AUTOPUSH_INTERVAL_MS) {
- return { start: false, reason: "throttled" };
- }
- return { start: true, head: input.head };
-}
-
-export interface AutopushDeps {
- env?: NodeJS.ProcessEnv;
- now?: number;
- head?: (repo: string) => string | null;
- /** Start the detached child; false when it could not be started. */
- start?: (repo: string) => boolean;
-}
-
-/**
- * The background push itself: `graft trail push <repo> --no-watch`, detached.
- *
- * `--no-watch` returns as soon as the digest is sent. The environment makes
- * sure nothing it runs can wait on a person: stdin is closed, stderr is a file
- * (so the push takes its no-terminal paths — no init picker, no spinner), git
- * and gh are told never to prompt, and AUTOPUSH_CHILD_ENV turns the sign-up
- * path, the only one that opens a browser, into a quiet exit.
- */
-export function startBackgroundPush(repo: string): boolean {
- let fd: number | null = null;
- try {
- fd = openSync(trailPushLogPath(repo), "w");
- const child = spawn(process.execPath, [graftCliPath(), "trail", "push", repo, "--no-watch"], {
- cwd: repo,
- detached: true,
- stdio: ["ignore", fd, fd],
- windowsHide: true,
- env: { ...process.env, [AUTOPUSH_CHILD_ENV]: "1", GIT_TERMINAL_PROMPT: "0", GH_PROMPT_DISABLED: "1" },
- });
- child.on("error", () => undefined);
- child.unref();
- return true;
- } catch {
- return false;
- } finally {
- // The child holds its own copy of the descriptor.
- if (fd !== null) {
- try {
- closeSync(fd);
- } catch {
- /* already closed */
- }
- }
- }
-}
-
-/**
- * Decide, stamp, start, and record the event. Returns the decision; never
- * throws, because it runs inside a hook.
- */
-export function maybeAutopush(repo: string, deps: AutopushDeps = {}): AutopushDecision {
- try {
- const env = deps.env ?? process.env;
- const now = deps.now ?? Date.now();
- const linked = readLink(repo) !== null && linkStoredHere(repo);
- // Nothing else is read — not even HEAD — for a repo without a trail.
- if (!linked) return { start: false, reason: "no_trail" };
- const enabled = autopushEnabled(repo, env);
- const head = enabled ? (deps.head ?? gitHead)(repo) : null;
- const state = readTrailPushState(repo);
- const decision = decideAutopush({ linked, enabled, head, state, now });
- if (!decision.start) {
- trackAutopush(repo, decision);
- return decision;
- }
- // Stamped first: a child that dies, or a second session opening in the same
- // second, must still count as this day's push.
- patchTrailPushState(repo, { autoPushAt: now, autoPushHead: decision.head });
- const started = (deps.start ?? startBackgroundPush)(repo);
- const out: AutopushDecision = started ? decision : { start: false, reason: "spawn_failed" };
- trackAutopush(repo, out);
- return out;
- } catch {
- return { start: false, reason: "spawn_failed" };
- }
-}
-
-/** The `trail_autopush` event: started, or skipped and why. */
-function trackAutopush(repo: string, d: AutopushDecision): void {
- if (!d.start && d.reason === "no_trail") return;
- track("trail_autopush", d.start ? { outcome: "started" } : { outcome: "skipped", reason: d.reason }, { repo });
-}
diff --git a/src/brain/claude-md.ts b/src/brain/claude-md.ts
deleted file mode 100644
index 2a1e912a..00000000
--- a/src/brain/claude-md.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-/**
- * The CLAUDE.md half of `graft trail pull` (and of `graft claude-md pull`, its
- * old name): write the CLAUDE.md changes accepted in Trail into this checkout's
- * instruction file.
- *
- * Trail compares the repository's CLAUDE.md with what its history says and
- * suggests edits and new sections; a person accepts some of them on the brain's
- * CLAUDE.md page. This fetches the accepted ones, applies them to the local
- * file, and tells Trail which it wrote so the page stops listing them.
- *
- * The file is edited line by line, never regenerated, so everything a change
- * does not touch comes back byte for byte. An edit whose text is no longer in
- * its section means the local file has moved on since Trail read it; that
- * change is reported and left, never guessed at. Same rules as Trail's own
- * ComposeClaudeMd, which is what the page's preview shows.
- */
-import { baseUrlFor, type BrainLink } from "./link.js";
-
-/** One accepted change, as Trail sends it. */
-export interface ClaudeMdChange {
- id: string;
- kind: "edit" | "add";
- /** edit: the section it rewrites. add: the new section's heading. */
- heading: string;
- /** add: the section it goes after; "" = end of file. */
- after_heading?: string;
- /** edit: the text to replace; "" = append to the section. */
- find?: string;
- text: string;
- reason?: string;
-}
-
-export interface ClaudeMdPull {
- /** The file Trail read, e.g. "CLAUDE.md"; "" when the repo had none. */
- path: string;
- head_sha: string;
- changes: ClaudeMdChange[];
-}
-
-export interface ApplyResult {
- text: string;
- /** Written by this pull. */
- written: ClaudeMdChange[];
- /** Already in the file (committed by someone else): nothing to write. */
- present: ClaudeMdChange[];
- /** Could not be placed; the file was left as it is for these. */
- skipped: Array<{ change: ClaudeMdChange; why: string }>;
-}
-
-/** GET /api/public/brains/:id/claude-md — the accepted changes. */
-export async function fetchAcceptedChanges(
- link: BrainLink,
- fetchImpl: typeof fetch = fetch,
-): Promise<ClaudeMdPull | { error: string; unsupported?: boolean; status?: number }> {
- const url = `${baseUrlFor(link)}/api/public/brains/${encodeURIComponent(link.brainId)}/claude-md`;
- try {
- const res = await fetchImpl(url, {
- headers: { authorization: `Bearer ${link.token}`, accept: "application/json" },
- signal: AbortSignal.timeout(15_000),
- });
- const body = await res.text();
- if (res.status === 404 || res.status === 503) {
- return { error: "this trail has no CLAUDE.md suggestions yet — its Trail may be older than the feature", unsupported: true };
- }
- // The status rides along so a watcher can tell a revoked token, which no
- // amount of waiting fixes, from a server having a bad minute.
- if (!res.ok) return { error: `Trail refused the pull: ${res.status} ${body.slice(0, 200)}`, status: res.status };
- const parsed = JSON.parse(body) as Partial<ClaudeMdPull>;
- return { path: parsed.path ?? "", head_sha: parsed.head_sha ?? "", changes: parsed.changes ?? [] };
- } catch (e) {
- return { error: `could not reach Trail: ${e instanceof Error ? e.message : e}` };
- }
-}
-
-/** POST /api/public/brains/:id/claude-md/applied — what this pull wrote. */
-export async function markApplied(link: BrainLink, ids: string[], fetchImpl: typeof fetch = fetch): Promise<boolean> {
- if (ids.length === 0) return true;
- const url = `${baseUrlFor(link)}/api/public/brains/${encodeURIComponent(link.brainId)}/claude-md/applied`;
- try {
- // Trail takes at most 100 per request.
- for (let i = 0; i < ids.length; i += 100) {
- const res = await fetchImpl(url, {
- method: "POST",
- headers: {
- authorization: `Bearer ${link.token}`,
- "content-type": "application/json",
- accept: "application/json",
- },
- body: JSON.stringify({ ids: ids.slice(i, i + 100) }),
- signal: AbortSignal.timeout(15_000),
- });
- if (!res.ok) return false;
- }
- return true;
- } catch {
- return false;
- }
-}
-
-interface Section {
- title: string;
- level: number;
- /** Line index of the heading. */
- head: number;
- /** One past the last line: the next heading at the same or a higher level. */
- end: number;
-}
-
-const HEADING = /^(#{1,6})\s+(.+?)\s*#*\s*$/;
-
-/** Every ATX heading outside code fences, with the lines it owns. */
-function sectionsOf(lines: string[]): Section[] {
- const heads: Array<{ line: number; level: number; title: string }> = [];
- let fence = false;
- lines.forEach((ln, i) => {
- const t = ln.trim();
- if (t.startsWith("```") || t.startsWith("~~~")) {
- fence = !fence;
- return;
- }
- if (fence) return;
- const m = HEADING.exec(ln);
- if (m) heads.push({ line: i, level: m[1]!.length, title: m[2]!.trim() });
- });
- return heads.map((h, i) => {
- let end = lines.length;
- for (let j = i + 1; j < heads.length; j++) {
- if (heads[j]!.level <= h.level) {
- end = heads[j]!.line;
- break;
- }
- }
- return { title: h.title, level: h.level, head: h.line, end };
- });
-}
-
-const norm = (s: string) => s.trim().toLowerCase();
-
-/** Trim the blank lines a section ends with, so appended text sits under its content. */
-function lastContentLine(lines: string[], s: Section): number {
- let i = s.end;
- while (i > s.head + 1 && lines[i - 1]!.trim() === "") i--;
- return i;
-}
-
-/**
- * Apply accepted changes to the file's text. Pure: reads nothing, writes
- * nothing, so the command and the tests share it.
- */
-export function applyChanges(original: string, changes: ClaudeMdChange[]): ApplyResult {
- const crlf = original.includes("\r\n");
- let lines = original.replace(/\r\n/g, "\n").split("\n");
- const out: ApplyResult = { text: original, written: [], present: [], skipped: [] };
-
- // Edits first, against headings that exist; then additions, which may go
- // after a section an edit just touched.
- const ordered = [...changes.filter((c) => c.kind === "edit"), ...changes.filter((c) => c.kind === "add")];
- for (const c of ordered) {
- const sections = sectionsOf(lines);
- if (c.kind === "edit") {
- const s = sections.find((x) => norm(x.title) === norm(c.heading));
- if (!s) {
- out.skipped.push({ change: c, why: `no “${c.heading}” section in the file` });
- continue;
- }
- const body = lines.slice(s.head + 1, s.end).join("\n");
- const text = c.text.replace(/\r\n/g, "\n");
- const find = (c.find ?? "").replace(/\r\n/g, "\n");
- if (text.trim() && body.includes(text.trim())) {
- out.present.push(c);
- continue;
- }
- if (!find) {
- const at = lastContentLine(lines, s);
- lines = [...lines.slice(0, at), ...text.trimEnd().split("\n"), ...lines.slice(at)];
- out.written.push(c);
- continue;
- }
- const idx = body.indexOf(find);
- if (idx < 0) {
- out.skipped.push({ change: c, why: `the text it rewrites is no longer in “${c.heading}”` });
- continue;
- }
- const next = body.slice(0, idx) + text + body.slice(idx + find.length);
- lines = [...lines.slice(0, s.head + 1), ...next.split("\n"), ...lines.slice(s.end)];
- out.written.push(c);
- continue;
- }
-
- // add
- if (sections.some((x) => norm(x.title) === norm(c.heading))) {
- out.present.push(c);
- continue;
- }
- const block = [`## ${c.heading.trim()}`, "", ...c.text.replace(/\r\n/g, "\n").trim().split("\n")];
- const after = c.after_heading ? sections.find((x) => norm(x.title) === norm(c.after_heading!)) : undefined;
- if (after) {
- const at = lastContentLine(lines, after);
- // A blank line either side, whatever the file had there.
- const tail = lines.slice(at);
- lines = [...lines.slice(0, at), "", ...block, ...(tail.length > 0 && tail[0]!.trim() !== "" ? [""] : []), ...tail];
- } else {
- while (lines.length > 0 && lines[lines.length - 1]!.trim() === "") lines.pop();
- lines = lines.length > 0 ? [...lines, "", ...block] : block;
- lines.push("");
- }
- out.written.push(c);
- }
-
- let text = lines.join("\n");
- if (out.written.length > 0 && !text.endsWith("\n")) text += "\n";
- out.text = out.written.length > 0 ? (crlf ? text.replace(/\n/g, "\r\n") : text) : original;
- return out;
-}
diff --git a/src/brain/connect.ts b/src/brain/connect.ts
deleted file mode 100644
index 4cd81d4d..00000000
--- a/src/brain/connect.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-/**
- * The one command a user runs to attach a brain: parse the handoff value,
- * store the link, pull the rules, write them into the agent files.
- */
-import {
- readLink,
- writeLink,
- fetchRules,
- writeRulesCache,
- readRulesCache,
- type BrainLink,
- type BrainRule,
-} from './link.js';
-import { writeBrainSections, type BrainWrite } from './wire.js';
-import { basename } from 'node:path';
-
-/**
- * Parse the `--trail` value.
- *
- * The onboarding page hands over one string so there is one thing to copy. Two
- * accepted shapes:
- *
- * `<brainId>:<token>` — the normal case, both halves in one paste
- * `<brainId>` — with the token in `GRAFT_BRAIN_TOKEN`, for CI, where
- * a secret must not appear in a command line
- *
- * A bare token with no brain id is rejected rather than guessed: pointing the
- * wrong brain at a repo would write another team's rules into it.
- */
-export function parseBrainArg(value: string): BrainLink | { error: string } {
- const raw = value.trim();
- if (!raw) return { error: 'empty --trail value' };
- const cut = raw.indexOf(':');
- if (cut > 0) {
- const brainId = raw.slice(0, cut).trim();
- const token = raw.slice(cut + 1).trim();
- if (!brainId || !token) return { error: 'expected --trail <brainId>:<token>' };
- return { brainId, token };
- }
- const envToken = process.env.GRAFT_BRAIN_TOKEN;
- if (!envToken) {
- return {
- error:
- 'expected --trail <brainId>:<token>, or a bare brain id with the token in GRAFT_BRAIN_TOKEN',
- };
- }
- return { brainId: raw, token: envToken };
-}
-
-/** What connecting a brain did, for the caller to print. */
-export interface ConnectResult {
- linked: boolean;
- ruleCount: number;
- writes: BrainWrite[];
- /** Set when the rules could not be fetched; the link is still stored. */
- warning?: string;
-}
-
-/**
- * Store the link, pull the rules once, and write them into the agent files.
- *
- * The link is stored even when the pull fails. That is deliberate: a token
- * typed correctly against a brain that is momentarily unreachable should not
- * have to be pasted again — `graft trail pull` retries, and `ask` degrades to
- * the code-only answer meanwhile.
- */
-export async function connectBrain(
- repo: string,
- link: BrainLink,
- opts: { home: string; ids?: string[]; fetchImpl?: typeof fetch } = { home: '' },
-): Promise<ConnectResult> {
- writeLink(repo, link);
- const rules = await fetchRules(link, opts.fetchImpl ?? fetch);
- if (rules === null) {
- return {
- linked: true,
- ruleCount: 0,
- writes: [],
- warning:
- 'could not reach the brain to pull its rules — the link is saved; run `graft trail pull` to retry',
- };
- }
- writeRulesCache(repo, { brainId: link.brainId, fetchedAt: Date.now(), rules });
- const writes = writeBrainSections(repo, opts.home, rules, basename(repo), opts.ids);
- return { linked: true, ruleCount: rules.length, writes };
-}
-
-/**
- * Re-pull the rules for an already-linked repo and rewrite the agent files.
- * Returns null when the repo has no brain linked.
- */
-export async function pullBrain(
- repo: string,
- opts: { home: string; ids?: string[]; fetchImpl?: typeof fetch },
-): Promise<ConnectResult | null> {
- const link = readLink(repo);
- if (!link) return null;
- return connectBrain(repo, link, opts);
-}
-
-/** The linked brain and its cached rule set, for `graft trail status`. */
-export function brainStatus(repo: string): {
- link: BrainLink | null;
- rules: BrainRule[];
- fetchedAt: number | null;
-} {
- const link = readLink(repo);
- const cache = readRulesCache(repo);
- return { link, rules: cache?.rules ?? [], fetchedAt: cache?.fetchedAt ?? null };
-}
diff --git a/src/brain/context-files.ts b/src/brain/context-files.ts
deleted file mode 100644
index 804698ce..00000000
--- a/src/brain/context-files.ts
+++ /dev/null
@@ -1,281 +0,0 @@
-/**
- * `graft trail pull`, for every context file rather than only the root CLAUDE.md.
- *
- * Trail suggests changes to the files a repository hands its coding agents —
- * AGENTS.md, a folder's own CLAUDE.md, Cursor rules, Claude skills — and a
- * person accepts some of them. This fetches the accepted ones and writes them.
- *
- * Edits and new sections go through the same line-by-line patcher as the root
- * CLAUDE.md (see claude-md.ts), so everything a change does not name comes back
- * byte for byte. A `create` carries a whole file, and it is never allowed to
- * overwrite a file someone wrote here: an existing file with other content is a
- * conflict to report, unless graft itself owns that file. A `replace` (how a
- * Cursor rule is edited) carries the whole new file and the whole file it was
- * computed against, and is written only while the file here is still that one.
- */
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
-import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
-import { applyChanges, type ClaudeMdChange } from "./claude-md.js";
-import { baseUrlFor, type BrainLink } from "./link.js";
-
-export type ContextFileKind = "agents_md" | "folder_claude_md" | "cursor_rule" | "skill";
-
-/** One accepted change to one context file. */
-export interface ContextFileChange {
- id: string;
- kind: "edit" | "add" | "create" | "replace";
- heading?: string;
- after_heading?: string;
- find?: string;
- /** edit/add: as in claude-md.ts. create/replace: the whole file. For
- * replace, `find` is the whole file the suggestion was computed against. */
- text: string;
- reason?: string;
-}
-
-export interface ContextFile {
- kind: ContextFileKind | string;
- path: string;
- exists?: boolean;
- managed_by_graft?: boolean;
- changes: ContextFileChange[];
-}
-
-export interface ContextFilesPull {
- head_sha: string;
- files: ContextFile[];
-}
-
-/**
- * Which picked agents read a file of this kind. A file whose readers were not
- * picked is neither listed nor written: `graft init` is where someone said which
- * agents this repo is for, and a pull must not quietly add files for others.
- */
-const READERS: Record<string, string[]> = {
- claude_md: ["claude"],
- folder_claude_md: ["claude"],
- skill: ["claude"],
- agents_md: ["agents", "hermes", "antigravity"],
- cursor_rule: ["cursor"],
-};
-
-/** The kind of a context file, from its path — for the root CLAUDE.md pull,
- * which names a path but no kind. */
-export function kindForPath(path: string): string {
- const p = path.replace(/\\/g, "/");
- const name = p.split("/").pop() ?? "";
- if (name === "CLAUDE.md") return p.includes("/") ? "folder_claude_md" : "claude_md";
- if (name === "AGENTS.md") return "agents_md";
- if (p.startsWith(".cursor/rules/")) return "cursor_rule";
- if (p.startsWith(".claude/skills/")) return "skill";
- return "";
-}
-
-/**
- * Whether a file of `kind` is for one of the `wired` agents. Everything passes
- * when nothing is wired — there is no choice to respect — and so does a kind
- * graft does not know, rather than dropping what Trail sent.
- */
-export function readByWired(kind: string, wired: readonly string[]): boolean {
- if (wired.length === 0) return true;
- const readers = READERS[kind];
- if (!readers) return true;
- return readers.some((r) => wired.includes(r));
-}
-
-/** The agents among `wired` that read a file of `kind`. */
-export function readersOf(kind: string, wired: readonly string[]): string[] {
- const readers = READERS[kind] ?? [];
- return wired.filter((w) => readers.includes(w));
-}
-
-/** GET /api/public/brains/:id/context-files. `unsupported` on a 404: an older Trail. */
-export async function fetchContextFiles(
- link: BrainLink,
- fetchImpl: typeof fetch = fetch,
-): Promise<ContextFilesPull | { unsupported: true } | { error: string; status?: number }> {
- const url = `${baseUrlFor(link)}/api/public/brains/${encodeURIComponent(link.brainId)}/context-files`;
- try {
- const res = await fetchImpl(url, {
- headers: { authorization: `Bearer ${link.token}`, accept: "application/json" },
- signal: AbortSignal.timeout(15_000),
- });
- const body = await res.text();
- if (res.status === 404) return { unsupported: true };
- if (!res.ok) return { error: `Trail refused the pull: ${res.status} ${body.slice(0, 200)}`, status: res.status };
- const parsed = JSON.parse(body) as Partial<ContextFilesPull>;
- const files = Array.isArray(parsed.files) ? parsed.files : [];
- return {
- head_sha: String(parsed.head_sha ?? ""),
- files: files
- .filter((f) => f && typeof f.path === "string")
- .map((f) => ({ ...f, changes: Array.isArray(f.changes) ? f.changes : [] })),
- };
- } catch (e) {
- return { error: `could not reach Trail: ${e instanceof Error ? e.message : e}` };
- }
-}
-
-/** POST /api/public/brains/:id/context-files/applied, 100 ids per request. */
-export async function markContextFilesApplied(link: BrainLink, ids: string[], fetchImpl: typeof fetch = fetch): Promise<boolean> {
- if (ids.length === 0) return true;
- const url = `${baseUrlFor(link)}/api/public/brains/${encodeURIComponent(link.brainId)}/context-files/applied`;
- try {
- for (let i = 0; i < ids.length; i += 100) {
- const res = await fetchImpl(url, {
- method: "POST",
- headers: {
- authorization: `Bearer ${link.token}`,
- "content-type": "application/json",
- accept: "application/json",
- },
- body: JSON.stringify({ ids: ids.slice(i, i + 100) }),
- signal: AbortSignal.timeout(15_000),
- });
- if (!res.ok) return false;
- }
- return true;
- } catch {
- return false;
- }
-}
-
-/** What a pull will do (or did) to one file. */
-export interface FilePlan {
- /** Repo-relative, forward slashes. */
- path: string;
- /** M: an existing file changes. A: a new file. "": nothing to write. */
- status: "M" | "A" | "";
- /** The file's new text, when status is set. */
- text?: string;
- written: ContextFileChange[];
- /** Already there: counts as applied, nothing to write. */
- present: ContextFileChange[];
- skipped: Array<{ change: ContextFileChange; why: string }>;
-}
-
-/**
- * The repo-relative form of a path Trail sent, or null when it points
- * anywhere but a file inside this checkout. Trail is trusted to suggest text,
- * not to choose where on this machine it lands.
- */
-export function safeRelPath(root: string, path: string): string | null {
- const raw = path.replace(/\\/g, "/").trim();
- if (!raw || isAbsolute(raw) || /^[a-zA-Z]:/.test(raw)) return null;
- const parts = raw.split("/");
- if (parts.some((p) => p === ".." || p === "")) return null;
- if (parts[0] === ".git") return null;
- const abs = resolve(root, normalize(raw));
- const rel = relative(resolve(root), abs);
- if (!rel || rel.startsWith("..") || isAbsolute(rel)) return null;
- return rel.split(sep).join("/");
-}
-
-/**
- * Work out one file's changes against what is on disk. Pure but for reading
- * the file, so the command, the dry run and the tests share it.
- */
-export function planContextFile(root: string, file: ContextFile): FilePlan {
- const rel = safeRelPath(root, file.path);
- const plan: FilePlan = { path: rel ?? file.path, status: "", written: [], present: [], skipped: [] };
- if (!rel) {
- for (const c of file.changes) plan.skipped.push({ change: c, why: "the path points outside this repo" });
- return plan;
- }
- const abs = join(root, rel);
- const existed = existsSync(abs);
- let original = "";
- if (existed) {
- try {
- original = readFileSync(abs, "utf8");
- } catch {
- for (const c of file.changes) plan.skipped.push({ change: c, why: "the file here could not be read" });
- return plan;
- }
- }
-
- let text = original;
- let changed = false;
- // Whole files first; the edits and sections after them may be relative to one.
- for (const c of file.changes.filter((x) => x.kind === "create")) {
- const want = c.text.replace(/\r\n/g, "\n");
- const have = text.replace(/\r\n/g, "\n");
- if (!existed && !changed) {
- text = c.text.endsWith("\n") ? c.text : `${c.text}\n`;
- changed = true;
- plan.written.push(c);
- } else if (have.trimEnd() === want.trimEnd()) {
- plan.present.push(c);
- } else if (file.managed_by_graft) {
- text = c.text.endsWith("\n") ? c.text : `${c.text}\n`;
- changed = true;
- plan.written.push(c);
- } else {
- plan.skipped.push({ change: c, why: "a file with other content is already there" });
- }
- }
-
- // Whole-file replacements, guarded by the text they were computed against.
- const same = (a: string, b: string) => a.replace(/\r\n/g, "\n").trimEnd() === b.replace(/\r\n/g, "\n").trimEnd();
- for (const c of file.changes.filter((x) => x.kind === "replace")) {
- if (same(text, c.text)) {
- plan.present.push(c);
- } else if (same(text, c.find ?? "") && (existed || changed || (c.find ?? "").trim() === "")) {
- text = c.text.endsWith("\n") ? c.text : `${c.text}\n`;
- changed = true;
- plan.written.push(c);
- } else {
- plan.skipped.push({ change: c, why: "the file changed here since Trail read it" });
- }
- }
-
- const patches = file.changes.filter((x) => x.kind === "edit" || x.kind === "add");
- if (patches.length > 0) {
- // A file that is not here yet is an empty one: an edit to a section of it
- // becomes that section, so the change lands rather than being skipped for
- // a heading nobody could have written.
- const fresh = !existed && !changed;
- const r = applyChanges(
- text,
- patches.map(
- (c) =>
- ({
- ...c,
- heading: c.heading ?? "",
- kind: fresh && c.kind === "edit" ? "add" : c.kind,
- ...(fresh && c.kind === "edit" ? { after_heading: "" } : {}),
- }) as ClaudeMdChange,
- ),
- );
- const byId = new Map(patches.map((c) => [c.id, c]));
- for (const w of r.written) plan.written.push(byId.get(w.id)!);
- for (const p of r.present) plan.present.push(byId.get(p.id)!);
- for (const s of r.skipped) plan.skipped.push({ change: byId.get(s.change.id)!, why: s.why });
- if (r.written.length > 0) {
- text = r.text;
- changed = true;
- }
- }
-
- if (changed && text !== original) {
- plan.status = existed ? "M" : "A";
- plan.text = text;
- }
- return plan;
-}
-
-/** Write a planned file, making its folder when it is new. */
-export function writePlannedFile(root: string, plan: FilePlan): void {
- if (!plan.status || plan.text === undefined) return;
- const abs = join(root, plan.path);
- mkdirSync(dirname(abs), { recursive: true });
- writeFileSync(abs, plan.text);
-}
-
-/** `+ Money · ~ Commands` — a new section is +, an edited one ~, a whole file nothing. */
-export function changeSummary(changes: Array<{ kind: string; heading?: string }>): string {
- return changes
- .filter((c) => c.kind === "add" || c.kind === "edit")
- .map((c) => `${c.kind === "add" ? "+" : "~"} ${c.heading ?? ""}`.trim())
- .join(" · ");
-}
diff --git a/src/brain/link.ts b/src/brain/link.ts
deleted file mode 100644
index 01fdb3f2..00000000
--- a/src/brain/link.ts
+++ /dev/null
@@ -1,231 +0,0 @@
-/**
- * The link between a repo's graft graph and a Trail brain.
- *
- * A brain holds the rules mined out of this repository's history — what the
- * team decided and why, which the code graph cannot see. Graft holds the code
- * and can say which symbols an answer touches. This module is the join: the
- * token identifying the brain, and the rules cached beside it so `ask` never
- * waits on the network.
- *
- * The link lives in the per-repo, git-ignored `.graft/config.json`, next to the
- * other persisted build choices. Not in `~/.graft/`: a brain belongs to one
- * repository, and two checkouts of different repos on one machine must not
- * share one.
- */
-import { readBuildConfig, patchBuildConfig, cacheDir, readJson, writeJsonAtomic } from '../util/state.js';
-import { join } from 'node:path';
-import { ensureGitignored, LINK_NOTE } from '../context/node-file.js';
-import { BUILD_CONFIG_DIR } from '../util/state.js';
-
-/** Default API host. Overridden by GRAFT_BRAIN_URL, for staging and self-hosted. */
-const DEFAULT_BRAIN_BASE_URL = 'https://agents.nanonets.com';
-
-/** How long a cached rule set is served before upkeep refreshes it. */
-export const RULES_TTL_MS = 6 * 60 * 60 * 1000; // 6 hours
-
-/**
- * The TTL used while the cache holds NO rules.
- *
- * A brain is connected during onboarding while it is still being mined, so the
- * first pull legitimately returns nothing. Six hours of that is the difference
- * between the feature working and the user concluding it does not: they wired
- * graft up, got an empty rulebook, and nothing would go back for the real one
- * until tomorrow. Two minutes costs one cheap request per session until the
- * rules land, and then the normal TTL takes over.
- */
-export const EMPTY_RULES_TTL_MS = 2 * 60 * 1000;
-
-/** One rule from the brain, anchored to a symbol in this repo. */
-export interface BrainRule {
- ruleId: string;
- /** A graft node id: `<path>#<QualifiedName>`. */
- symbol: string;
- /** The symbol's body hash when the rule was mined; '' when unrecorded. */
- fingerprint: string;
- rule: string;
- /** Deep link to the commit or pull request that established it. */
- sourceUrl?: string;
-}
-
-/** The cached rule set, as stored under the repo's graft cache. */
-export interface RulesCache {
- brainId: string;
- fetchedAt: number;
- rules: BrainRule[];
- /** When a refresh was last ATTEMPTED, successful or not. Separate from
- * `fetchedAt`, which records when rules last actually arrived: without the
- * distinction, a brain that is still building would be re-checked on every
- * single command, because its `fetchedAt` never advances. */
- checkedAt?: number;
-}
-
-/** The persisted brain link. */
-export interface BrainLink {
- brainId: string;
- /** Workspace API key (`nn...`). Stored in the git-ignored `.graft/`. */
- token: string;
- /** Set only when the user pointed graft at a non-default host. */
- baseUrl?: string;
-}
-
-/**
- * The link for repo `dir`, or null when it has none.
- *
- * `GRAFT_BRAIN_TOKEN` / `GRAFT_BRAIN_ID` override the stored pair, so CI can
- * attach a brain without writing to the checkout.
- */
-export function readLink(dir: string): BrainLink | null {
- const envToken = process.env.GRAFT_BRAIN_TOKEN;
- const envBrain = process.env.GRAFT_BRAIN_ID;
- if (envToken && envBrain) {
- return { brainId: envBrain, token: envToken, baseUrl: process.env.GRAFT_BRAIN_URL };
- }
- const stored = readBuildConfig(dir)?.brain;
- if (!stored?.brainId || !stored?.token) return null;
- return stored;
-}
-
-/** Persist the link for repo `dir`, merging into any existing build config.
- *
- * The write is what creates `.graft/config.json`, and that file holds the read
- * token — which is exactly why this is also where it gets ignored. The comment
- * on {@link BrainLink} has claimed `.graft/` was "git-ignored" since the day it
- * was written, and nothing ever made it true: `ensureGitignored` only ever ran
- * for the graph cache. Every repository anyone ran `graft trail connect` in was
- * therefore one `git add -A` away from publishing a credential. */
-export function writeLink(dir: string, link: BrainLink): void {
- patchBuildConfig(dir, { brain: link });
- ensureGitignored(dir, join(dir, BUILD_CONFIG_DIR), LINK_NOTE);
-}
-
-/** Forget the link for repo `dir`. Leaves the cached rules for `uninstall` to remove. */
-export function clearLink(dir: string): void {
- patchBuildConfig(dir, { brain: undefined });
-}
-
-/** Where the rule cache lives: beside the graph, since it is derived data. */
-export function rulesCachePath(dir: string): string {
- return join(cacheDir(dir), 'brain-rules.json');
-}
-
-export function readRulesCache(dir: string): RulesCache | null {
- return readJson<RulesCache>(rulesCachePath(dir));
-}
-
-export function writeRulesCache(dir: string, cache: RulesCache): void {
- writeJsonAtomic(rulesCachePath(dir), cache, true);
-}
-
-/**
- * Whether a cached set is old enough to refetch.
- *
- * Keyed off the last ATTEMPT, not the last success, and with a much shorter
- * window while the cache is empty — see EMPTY_RULES_TTL_MS for why that case
- * is the one that matters.
- */
-export function cacheIsStale(cache: RulesCache | null, now = Date.now()): boolean {
- if (!cache) return true;
- const ttl = cache.rules.length === 0 ? EMPTY_RULES_TTL_MS : RULES_TTL_MS;
- return now - (cache.checkedAt ?? cache.fetchedAt) > ttl;
-}
-
-/** Record that a refresh was attempted, without claiming rules arrived. */
-export function markRulesChecked(dir: string, now = Date.now()): void {
- const cache = readRulesCache(dir);
- if (!cache) return;
- writeRulesCache(dir, { ...cache, checkedAt: now });
-}
-
-/**
- * The base URL for a link, honouring the env override first so a misconfigured
- * stored value can always be corrected without editing a file.
- */
-export function baseUrlFor(link: BrainLink): string {
- return (process.env.GRAFT_BRAIN_URL || link.baseUrl || DEFAULT_BRAIN_BASE_URL).replace(/\/+$/, '');
-}
-
-/** The API host before there is a link to read one from: signing up. */
-export function apiBaseUrl(): string {
- return (process.env.GRAFT_BRAIN_URL || DEFAULT_BRAIN_BASE_URL).replace(/\/+$/, '');
-}
-
-/** A sign-up an agent-run push started and has not collected yet. */
-export interface PendingSignup {
- /** The state in the link, which is what claims the trail. */
- state: string;
- /** The repository the link was for, so a changed remote starts over. */
- repo: string;
- createdAt: number;
-}
-
-/** The sign-up waiting on repo `dir`, or null when there is none or it is too
- * old to claim, or it was for a different repository. */
-export function readPendingSignup(dir: string, repo: string, maxAgeMs: number, now = Date.now()): PendingSignup | null {
- const p = readBuildConfig(dir)?.pendingSignup;
- if (!p?.state || p.repo !== repo || !(now - p.createdAt < maxAgeMs)) return null;
- return p;
-}
-
-/** Save the sign-up an agent-run push just started. Git-ignored like the link,
- * because the state claims a read token. */
-export function writePendingSignup(dir: string, pending: PendingSignup): void {
- patchBuildConfig(dir, { pendingSignup: pending });
- ensureGitignored(dir, join(dir, BUILD_CONFIG_DIR), LINK_NOTE);
-}
-
-export function clearPendingSignup(dir: string): void {
- patchBuildConfig(dir, { pendingSignup: undefined });
-}
-
-/** Timeout for one rules fetch. Short: `ask` must never block on this. */
-const FETCH_TIMEOUT_MS = 5000;
-
-interface AnchorsResponse {
- anchors?: Array<{
- rule_id?: string;
- symbol?: string;
- fingerprint?: string;
- rule?: string;
- source_url?: string;
- }>;
-}
-
-/**
- * Fetch the brain's symbol-anchored rules.
- *
- * Returns null on any failure — an unreachable brain, a revoked token, a
- * malformed body. Never throws: `ask` degrades to the code-only answer it gave
- * before a brain was attached, which is the whole reason the cache exists.
- */
-export async function fetchRules(
- link: BrainLink,
- fetchImpl: typeof fetch = fetch,
-): Promise<BrainRule[] | null> {
- // The PUBLIC, token-authenticated route: graft runs on a laptop with no
- // session, and the token it holds is scoped to this one brain rather than the
- // workspace. The protected route is for the app itself.
- const url = `${baseUrlFor(link)}/api/public/brains/${encodeURIComponent(link.brainId)}/rules/anchors`;
- try {
- const res = await fetchImpl(url, {
- headers: { authorization: `Bearer ${link.token}`, accept: 'application/json' },
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
- });
- if (!res.ok) return null;
- const body = (await res.json()) as AnchorsResponse;
- if (!Array.isArray(body.anchors)) return null;
- const out: BrainRule[] = [];
- for (const a of body.anchors) {
- if (!a?.symbol || !a?.rule) continue;
- out.push({
- ruleId: String(a.rule_id ?? ''),
- symbol: a.symbol,
- fingerprint: String(a.fingerprint ?? ''),
- rule: a.rule,
- sourceUrl: a.source_url || undefined,
- });
- }
- return out;
- } catch {
- return null;
- }
-}
diff --git a/src/brain/pull.ts b/src/brain/pull.ts
deleted file mode 100644
index 00bbd914..00000000
--- a/src/brain/pull.ts
+++ /dev/null
@@ -1,331 +0,0 @@
-/**
- * `graft trail pull`: one command for both things a trail hands this repo.
- *
- * First the rules, refreshed into graft's own blocks in the agent files (what
- * `graft trail pull` always did). Then every change accepted in Trail, for every
- * context file the picked agents read — the root CLAUDE.md (what `graft
- * claude-md pull` did, and still does, as an alias of this), and then AGENTS.md,
- * folder CLAUDE.md files, Cursor rules and skills when Trail serves them.
- *
- * Files for agents that were not picked are neither listed nor written.
- */
-import { isAbsolute, relative } from "node:path";
-import { connectBrain, type ConnectResult } from "./connect.js";
-import { fetchAcceptedChanges, markApplied } from "./claude-md.js";
-import {
- changeSummary,
- fetchContextFiles,
- kindForPath,
- markContextFilesApplied,
- planContextFile,
- readByWired,
- readersOf,
- writePlannedFile,
- type ContextFile,
- type FilePlan,
-} from "./context-files.js";
-import type { BrainLink } from "./link.js";
-import { reviewUrl } from "./signup.js";
-import { fetchRepoState, type RepoState, type Suggestions } from "./watch.js";
-import { CONTEXT_FILE_KINDS, countBucket, type TrailPullOutcome } from "../telemetry/contract.js";
-import { track } from "../telemetry/track.js";
-
-export interface PullOptions {
- home: string;
- /** The agents this repo is wired for; empty means no choice was recorded. */
- wired: string[];
- dryRun?: boolean;
- fetchImpl?: typeof fetch;
- write?: (line: string) => void;
-}
-
-/** Repo-relative, forward slashes, for printing. */
-function show(repo: string, path: string): string {
- const rel = isAbsolute(path) ? relative(repo, path) : path;
- return rel.split("\\").join("/");
-}
-
-/** The rules line: how many, and which files they are in. */
-export function rulesLine(repo: string, res: ConnectResult): string | null {
- if (res.warning) return `⚠ ${res.warning}`;
- if (res.ruleCount === 0) return "· the trail has no rules yet — run graft trail push to read this repo into it";
- const n = res.ruleCount.toLocaleString("en-US");
- const where = res.writes.map((w) => show(repo, w.path)).join(", ");
- const rules = `${n} rule${res.ruleCount === 1 ? "" : "s"}`;
- if (!where) return `✓ ${rules} pulled · no instruction file to write them into — graft ask still carries them`;
- if (res.writes.every((w) => w.action === "unchanged")) return `✓ rules already current · ${n} in ${where}`;
- return `✓ ${rules} refreshed in ${where}`;
-}
-
-/** `a, b and c`. */
-function joinAnd(items: string[]): string {
- if (items.length <= 1) return items.join("");
- return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
-}
-
-/**
- * Trail's suggestions, cut to the files the wired agents read: how many, and
- * whose files they are (`the files claude and cursor read`).
- *
- * Every suggestion Trail has made, whatever became of it — the counts it sends
- * do not say which are still waiting for review and which were dismissed.
- */
-export function suggestedFor(s: Suggestions | undefined, wired: string[]): { count: number; whose: string } {
- if (!s) return { count: 0, whose: "" };
- let count = 0;
- const kinds = new Set<string>();
- if (s.claudeMd > 0 && readByWired("claude_md", wired)) {
- count += s.claudeMd;
- kinds.add("claude_md");
- }
- if (s.files) {
- for (const f of s.files) {
- if (f.changes <= 0 || !readByWired(f.kind, wired)) continue;
- count += f.changes;
- kinds.add(f.kind);
- }
- } else if (s.contextFiles > 0) {
- // No per-file list from this Trail, so no way to cut it to the wired agents'
- // files: the count is Trail's total.
- count += s.contextFiles;
- for (const k of ["agents_md", "folder_claude_md", "cursor_rule", "skill"]) kinds.add(k);
- }
- const readers = wired.length
- ? wired.filter((w) => [...kinds].some((k) => readersOf(k, [w]).length > 0))
- : [];
- return { count, whose: readers.length ? `the files ${joinAnd(readers)} read` : "this repo's context files" };
-}
-
-/**
- * The suggestions line after a build:
- * `● 18 suggestions for the files claude, agents and cursor read`. Null when
- * there are none to mention.
- */
-export function suggestionsLine(s: Suggestions | undefined, wired: string[], again: boolean): string | null {
- const { count, whose } = suggestedFor(s, wired);
- if (count === 0) return null;
- return `● ${count.toLocaleString("en-US")} ${again ? "new " : ""}suggestion${count === 1 ? "" : "s"} for ${whose}`;
-}
-
-/**
- * What a pull says about the suggestions it did not write:
- * `● 20 suggested so far for the files claude read, 2 of them accepted`.
- *
- * This is what lets an agent watching the trail say "there are suggestions
- * waiting for you" before anything has been accepted. "So far", because the
- * build keeps adding them after the push returns. Null when Trail sent no
- * counts, or counts that cannot hold what was accepted.
- */
-export function suggestedLine(suggested: { count: number; whose: string }, accepted: number): string | null {
- if (suggested.count === 0 || suggested.count < accepted) return null;
- const taken = accepted === 0 ? "none accepted yet" : `${accepted.toLocaleString("en-US")} of them accepted`;
- return `● ${suggested.count.toLocaleString("en-US")} suggested so far for ${suggested.whose}, ${taken}`;
-}
-
-/** Everything the pull will write, file by file, with where each change came from. */
-export interface Planned {
- plan: FilePlan;
- source: "claude-md" | "context-files";
- kind: string;
-}
-
-/** What Trail holds for this checkout right now, planned against the files on disk. */
-export interface Gathered {
- /** Every file with an accepted change for the wired agents, planned. */
- planned: Planned[];
- /** Accepted changes Trail still lists for the wired agents' files, whatever
- * the plan makes of them. */
- accepted: number;
- /** What Trail has suggested for those files, or null when the counts could
- * not be read (a failed request, as opposed to a Trail that sends none). */
- suggested: { count: number; whose: string } | null;
- /** Each request that failed, in the order the pull reports them. `status` is
- * the HTTP status when Trail answered, absent when it could not be reached —
- * the difference between a revoked token and a blip. */
- errors: Array<{ message: string; status?: number }>;
-}
-
-/**
- * Read everything Trail has accepted for this repo and plan it against disk,
- * without writing a byte or telling Trail anything.
- *
- * The one read both `graft trail pull` and `graft trail watch` (and the
- * session-start hook's quick look) are built on, so a watcher that says "3
- * accepted changes are ready" is counting exactly what the pull will write. The
- * three requests go out together: the hook gives this three seconds, and three
- * in a row would spend them.
- *
- * `repoState` is for a caller that started the counts request earlier, as the
- * pull does, so it runs beside the rules refresh rather than after it.
- */
-export async function gatherPull(
- repo: string,
- link: BrainLink,
- wired: string[],
- fetchImpl: typeof fetch = fetch,
- repoState: Promise<RepoState | null> = fetchRepoState(link, fetchImpl),
-): Promise<Gathered> {
- const [md, ctx, state] = await Promise.all([fetchAcceptedChanges(link, fetchImpl), fetchContextFiles(link, fetchImpl), repoState]);
- const planned: Planned[] = [];
- const errors: Gathered["errors"] = [];
- let accepted = 0;
-
- // The root CLAUDE.md first, then every other context file: the order the
- // pull has always listed them in.
- if ("error" in md) {
- if (!md.unsupported) errors.push({ message: md.error, ...(md.status ? { status: md.status } : {}) });
- } else if (md.changes.length > 0) {
- const file: ContextFile = { kind: kindForPath(md.path || "CLAUDE.md"), path: md.path || "CLAUDE.md", changes: md.changes };
- if (readByWired(file.kind, wired)) {
- accepted += file.changes.length;
- planned.push({ plan: planContextFile(repo, file), source: "claude-md", kind: file.kind });
- }
- }
-
- if ("error" in ctx) {
- errors.push({ message: ctx.error, ...(ctx.status ? { status: ctx.status } : {}) });
- } else if (!("unsupported" in ctx)) {
- for (const file of ctx.files) {
- if (file.changes.length === 0 || !readByWired(file.kind, wired)) continue;
- accepted += file.changes.length;
- planned.push({ plan: planContextFile(repo, file), source: "context-files", kind: file.kind });
- }
- }
-
- return { planned, accepted, suggested: state ? suggestedFor(state.suggestions, wired) : null, errors };
-}
-
-/**
- * The `trail_pulled` event for one pull. Only the outcome, which kinds of file
- * were written, and bucketed counts leave the machine — see TELEMETRY.md.
- */
-function trackPull(repo: string, home: string | undefined, outcome: TrailPullOutcome, planned: Planned[] = [], suggested = 0): void {
- const wrote = planned.filter((p) => p.plan.status && p.plan.written.length > 0);
- const kinds = [...new Set(wrote.map((p) => p.kind))]
- .filter((k) => (CONTEXT_FILE_KINDS as readonly string[]).includes(k))
- .sort()
- .join(",");
- track(
- "trail_pulled",
- {
- outcome,
- kinds,
- files_bucket: countBucket(wrote.length),
- changes_bucket: countBucket(wrote.reduce((n, p) => n + p.plan.written.length, 0)),
- skipped_bucket: countBucket(planned.reduce((n, p) => n + p.plan.skipped.length, 0)),
- suggested_bucket: countBucket(suggested),
- },
- { repo, home },
- );
-}
-
-/**
- * Run the pull. Returns the exit code; every line goes through `write`.
- */
-export async function runTrailPull(repo: string, link: BrainLink, opts: PullOptions): Promise<number> {
- const write = opts.write ?? ((l: string) => console.error(l));
- const fetchImpl = opts.fetchImpl ?? fetch;
- let code = 0;
- // Read beside everything else: it only adds a line, and a Trail that cannot
- // answer it costs the pull nothing.
- const repoState = fetchRepoState(link, fetchImpl);
-
- // 1. The rules. Skipped on a dry run, which writes nothing at all.
- if (!opts.dryRun) {
- const res = await connectBrain(repo, link, {
- home: opts.home,
- ids: opts.wired.length > 0 ? opts.wired : undefined,
- fetchImpl,
- });
- const line = rulesLine(repo, res);
- if (line) write(line);
- if (res.warning) code = 1;
- }
-
- // 2. Accepted changes: the root CLAUDE.md, then every other context file.
- const { planned, accepted, suggested: counted, errors } = await gatherPull(repo, link, opts.wired, fetchImpl, repoState);
- for (const e of errors) {
- write(`✗ ${e.message}`);
- code = 1;
- }
-
- const suggested = counted ?? { count: 0, whose: "" };
- const waiting = suggestedLine(suggested, accepted);
-
- if (accepted === 0) {
- if (code === 0) {
- if (waiting) {
- write(waiting);
- write(` review: ${reviewUrl(link.brainId)}`);
- } else {
- write("· nothing accepted in Trail yet — review:");
- write(` ${reviewUrl(link.brainId)}`);
- }
- }
- trackPull(repo, opts.home, code === 0 ? "nothing_accepted" : "error", [], suggested.count);
- return code;
- }
-
- const writing = planned.filter((p) => p.plan.status);
- const changes = writing.reduce((n, p) => n + p.plan.written.length, 0);
- if (writing.length > 0) {
- write(`✓ ${opts.dryRun ? "would write" : "wrote"} ${changes} accepted change${changes === 1 ? "" : "s"}`);
- const width = Math.max(30, ...writing.map((p) => p.plan.path.length)) + 2;
- for (const { plan } of writing) {
- const summary = changeSummary(plan.written);
- write(` ${plan.status} ${summary ? plan.path.padEnd(width) : plan.path}${summary}`.trimEnd());
- }
- } else if (planned.some((p) => p.plan.present.length > 0)) {
- write("✓ every accepted change is already in these files");
- }
-
- for (const { plan } of planned) {
- for (const s of plan.skipped) {
- const what = s.change.kind === "edit" || s.change.kind === "add" ? `${changeSummary([s.change])} in ${plan.path}` : plan.path;
- write(`⚠ skipped ${what} — ${s.why}; edit it in Trail, then pull again`);
- code = 1;
- }
- }
-
- if (waiting) {
- write(waiting);
- write(` review: ${reviewUrl(link.brainId)}`);
- }
-
- if (opts.dryRun) {
- write("· dry run — nothing written, and Trail was not told");
- trackPull(repo, opts.home, "dry_run", planned, suggested.count);
- return code;
- }
-
- for (const { plan } of writing) {
- try {
- writePlannedFile(repo, plan);
- } catch (e) {
- write(`✗ could not write ${plan.path}: ${e instanceof Error ? e.message : e}`);
- // Nothing from a file that was not written is reported as applied.
- plan.written = [];
- plan.present = [];
- code = 1;
- }
- }
-
- // Written now or already there: either way Trail should stop listing it.
- const done = (source: Planned["source"]) =>
- planned.filter((p) => p.source === source).flatMap((p) => [...p.plan.written, ...p.plan.present].map((c) => c.id));
- const told = (await markApplied(link, done("claude-md"), fetchImpl)) && (await markContextFilesApplied(link, done("context-files"), fetchImpl));
- if (!told) write("⚠ could not tell Trail which changes were written; it may still list them");
- if (writing.length > 0) write("· review with git diff, then commit");
- const anyWritten = planned.some((p) => p.plan.status && p.plan.written.length > 0);
- const anyPresent = planned.some((p) => p.plan.present.length > 0);
- const anySkipped = planned.some((p) => p.plan.skipped.length > 0);
- const outcome: TrailPullOutcome = anyWritten
- ? "written"
- : anyPresent
- ? "already_present"
- : anySkipped
- ? "skipped"
- : "error";
- trackPull(repo, opts.home, outcome, planned, suggested.count);
- return code;
-}
diff --git a/src/brain/push.ts b/src/brain/push.ts
deleted file mode 100644
index 782b76c5..00000000
--- a/src/brain/push.ts
+++ /dev/null
@@ -1,394 +0,0 @@
-/**
- * Building a brain from the repository already on this machine.
- *
- * The server path needs graft's GitHub App installed on the repo, which is an
- * admin action on someone else's org and the first thing asked of a person who
- * has not seen a single rule yet. For a private repository it is often simply
- * unavailable.
- *
- * This is the way round that: the clone is already here, and the user is
- * already authenticated to GitHub for their own work. So read it locally and
- * send up the same digest the server would have built.
- *
- * What leaves the machine is what people wrote — commit messages, pull-request
- * comments, the docs and config already in the tree — plus symbol ids and
- * hashes. No file contents, no diffs, no source.
- */
-import { spawnSync } from "node:child_process";
-import {
- buildDigest,
- newThreadReadCache,
- readCommits,
- readSymbols,
- readThreads,
- type HistoryThread,
- type RepoDigest,
- type ThreadReadCache,
-} from "../app/history.js";
-import {
- budgetSources,
- readAgentInstructions,
- readBranchProtection,
- readCodeowners,
- readCodifiedRules,
- readDecisionDocs,
- readDeclinedIssues,
- readReverts,
- readTestNames,
-} from "../app/sources.js";
-import type { GraphV1 } from "../graph/types.js";
-import { readStamp, wiredHostIds } from "../upkeep.js";
-import { baseUrlFor, type BrainLink } from "./link.js";
-import { postDigestOnce, uploadDigest, type UploadCaps, type UploadOptions } from "./upload.js";
-
-/** What a local ingest read, for the caller to print. */
-export interface PushResult {
- jobId: string;
- repo: string;
- commits: number;
- threads: number;
- symbols: number;
- sources: number;
- /** Set when discussion could not be read; the ingest still went ahead. */
- warning?: string;
-}
-
-function git(root: string, args: string[]): string | null {
- const res = spawnSync("git", ["-c", "core.quotePath=false", ...args], {
- cwd: root,
- encoding: "utf8",
- stdio: ["ignore", "pipe", "pipe"],
- });
- if (res.error || res.status !== 0 || typeof res.stdout !== "string") return null;
- return res.stdout.trim();
-}
-
-/**
- * owner/name for this checkout, from its origin remote.
- *
- * Only GitHub, because the discussion reader and the forge links are
- * GitHub-shaped; another forge would need its own reader, not a looser regex
- * here that produces links to nowhere.
- */
-export function repoSlugFromGit(root: string): { owner: string; name: string } | null {
- const url = git(root, ["remote", "get-url", "origin"]);
- if (!url) return null;
- const m = url.match(/github\.com[:/]+([^/]+)\/(.+?)(?:\.git)?\/?$/i);
- if (!m) return null;
- return { owner: m[1], name: m[2] };
-}
-
-/** The branch to attribute the ingest to. */
-function currentBranch(root: string): string {
- const head = git(root, ["rev-parse", "--abbrev-ref", "HEAD"]);
- return head && head !== "HEAD" ? head : "";
-}
-
-/**
- * A GitHub token from wherever the user already keeps one.
- *
- * `gh auth token` first, because anyone who works with private repositories on
- * the command line has it and it needs no setup at all. The env vars are the
- * CI path. Absent, the ingest still runs on commits alone — pull-request
- * discussion is the richest source, not a required one.
- */
-export function githubToken(): string | null {
- const env = process.env.GH_TOKEN || process.env.GITHUB_TOKEN;
- if (env) return env;
- const res = spawnSync("gh", ["auth", "token"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
- const out = typeof res.stdout === "string" ? res.stdout.trim() : "";
- return res.status === 0 && out ? out : null;
-}
-
-/** Whether the repository is private, so the digest records it honestly. */
-async function isPrivate(owner: string, name: string, token: string | null, fetchImpl: typeof fetch): Promise<boolean> {
- if (!token) return true; // unknown counts as private
- try {
- const res = await fetchImpl(`https://api.github.com/repos/${owner}/${name}`, {
- headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json" },
- });
- if (!res.ok) return true;
- return ((await res.json()) as { private?: boolean }).private !== false;
- } catch {
- return true;
- }
-}
-
-/** What the brain is waiting for, when it is waiting for something. */
-export interface ExpectedRepo {
- slug: string;
- status: string;
- brainName: string;
- /** Rules the trail already holds; 0 before its first build. */
- ruleCount: number;
- /** The brain accepts an early upload (see pushEarlyDigest). */
- earlyUpload: boolean;
- /** POST /repo takes a gzipped body (`gzip_upload`). */
- gzipUpload: boolean;
- /** The chunked /repo/uploads routes exist (`chunked_upload`). */
- chunkedUpload: boolean;
- /** GET /events streams the build (`events`). */
- events: boolean;
-}
-
-/**
- * The repository this brain expects, or null when it expects none.
- *
- * The website records it when the user chooses the local route, so this is how
- * the CLI knows whether the directory it is standing in is the one they asked
- * for. Mining the wrong repo into a brain is silent and very hard to notice
- * afterwards — the rules simply describe someone else's codebase — so the round
- * trip is worth it.
- *
- * The same read says what the server can take: gzip, chunks, a live event
- * stream. Every flag defaults to off, so an older Trail gets exactly the
- * requests it always did.
- *
- * Null on any failure, which keeps an older brain (or an unreachable one)
- * working exactly as it did before this check existed.
- */
-export async function fetchExpectedRepo(link: BrainLink, fetchImpl: typeof fetch = fetch): Promise<ExpectedRepo | null> {
- try {
- const res = await fetchImpl(`${baseUrlFor(link)}/api/public/brains/${encodeURIComponent(link.brainId)}/repo`, {
- headers: { authorization: `Bearer ${link.token}`, accept: "application/json" },
- signal: AbortSignal.timeout(5000),
- });
- if (!res.ok) return null;
- const body = (await res.json()) as {
- repo?: { slug?: string; status?: string; rule_count?: number } | null;
- brain_name?: string;
- early_upload?: boolean;
- gzip_upload?: boolean;
- chunked_upload?: boolean;
- events?: boolean;
- };
- if (!body.repo?.slug) return null;
- return {
- slug: body.repo.slug,
- status: String(body.repo.status ?? ""),
- brainName: String(body.brain_name ?? ""),
- ruleCount: typeof body.repo.rule_count === "number" && body.repo.rule_count > 0 ? body.repo.rule_count : 0,
- earlyUpload: body.early_upload === true,
- gzipUpload: body.gzip_upload === true,
- chunkedUpload: body.chunked_upload === true,
- events: body.events === true,
- };
- } catch {
- return null;
- }
-}
-
-/** The upload capabilities an expected-repo read advertised. */
-export function uploadCaps(expected: ExpectedRepo | null): UploadCaps {
- return { gzip: expected?.gzipUpload === true, chunked: expected?.chunkedUpload === true };
-}
-
-/** Whether two repo slugs name the same repository. GitHub is case-insensitive. */
-export function sameRepo(a: string, b: string): boolean {
- return a.trim().toLowerCase() === b.trim().toLowerCase();
-}
-
-/** How many of the newest pull requests and commits the early upload carries —
- * what Trail's quick CLAUDE.md pass reads, and no more. */
-export const EARLY_THREADS = 30;
-export const EARLY_COMMITS = 80;
-
-/**
- * What one push reads once and shares between its early and full digests: the
- * repository's identity, the GitHub token, whether it is private, and every
- * request already made to GitHub for its pull requests.
- */
-export interface PushContext {
- owner: string;
- name: string;
- token: string | null;
- fetchImpl: typeof fetch;
- headSha: string;
- branch: string;
- /** Asked once, when first needed. */
- isPrivate: () => Promise<boolean>;
- threads: ThreadReadCache;
-}
-
-/** The shared context for a push from `root`, or null without a GitHub origin. */
-export function pushContext(root: string, opts: { fetchImpl?: typeof fetch } = {}): PushContext | null {
- const slug = repoSlugFromGit(root);
- if (!slug) return null;
- const fetchImpl = opts.fetchImpl ?? fetch;
- const token = githubToken();
- let privacy: Promise<boolean> | null = null;
- return {
- owner: slug.owner,
- name: slug.name,
- token,
- fetchImpl,
- headSha: git(root, ["rev-parse", "HEAD"]) ?? "",
- branch: currentBranch(root),
- isPrivate: () => (privacy ??= isPrivate(slug.owner, slug.name, token, fetchImpl)),
- threads: newThreadReadCache(),
- };
-}
-
-/**
- * The early upload: the instruction files, the newest pull requests and the
- * newest commits, read before the rest of the history.
- *
- * Reading the history is most of a push's wait — up to 200 pull requests at two
- * GitHub calls each — and Trail's first CLAUDE.md suggestions need none of it
- * beyond the newest few. Sent first, they start while the full read is still
- * going here, and the full upload that follows mines as before.
- *
- * Only the newest commits are read here, not the thousand the full read takes,
- * so nothing but these few requests stands between the push starting and Trail
- * starting. The pull requests go through the shared cache, so the full read
- * asks GitHub for none of them again — not even one still in flight.
- *
- * Null when there is nothing worth sending early.
- */
-export async function buildEarlyDigest(
- root: string,
- opts: { fetchImpl?: typeof fetch; context?: PushContext } = {},
-): Promise<{ digest: RepoDigest; threads: HistoryThread[] } | null> {
- const ctx = opts.context ?? pushContext(root, opts);
- if (!ctx) return null;
- // Oldest first, like the full read, so the newest are the tail.
- const commits = readCommits(root, EARLY_COMMITS);
- if (commits.length === 0) return null;
- let threads: HistoryThread[] = [];
- if (ctx.token) {
- try {
- threads = await readThreads(ctx.owner, ctx.name, ctx.token, ctx.fetchImpl as never, undefined, EARLY_THREADS, undefined, ctx.threads);
- } catch {
- threads = [];
- }
- }
- const digest = buildDigest({
- owner: ctx.owner,
- name: ctx.name,
- headSha: ctx.headSha,
- defaultBranch: ctx.branch,
- isPrivate: await ctx.isPrivate(),
- commits,
- threads,
- symbols: [],
- sources: budgetSources(readAgentInstructions(root)),
- autoApprove: true,
- agents: pickedAgents(root),
- });
- return { digest, threads };
-}
-
-/**
- * The agents this repo is wired for — what `graft init` recorded plus what is on
- * disk, the same set `graft trail pull` filters by — so Trail can show only the
- * context files those agents read. Empty before the first init; Trail then
- * shows every kind.
- */
-export function pickedAgents(root: string): string[] {
- try {
- return [...new Set([...(readStamp(root)?.hosts ?? []), ...wiredHostIds(root)])];
- } catch {
- return [];
- }
-}
-
-/** Send the early upload. Best-effort: false on any failure, and the full
- * upload still does everything. Gzipped when the server takes it. */
-export async function pushEarlyDigest(
- link: BrainLink,
- digest: RepoDigest,
- fetchImpl: typeof fetch = fetch,
- opts: { gzip?: boolean } = {},
-): Promise<boolean> {
- try {
- const res = await postDigestOnce(link, digest, { gzip: opts.gzip, fetchImpl, query: "?stage=early", timeoutMs: 15_000 });
- if (!res.ok) return false;
- return ((await res.json()) as { early?: boolean }).early === true;
- } catch {
- return false;
- }
-}
-
-/** Build the digest for the checkout at `root`. Reads nothing but text. */
-export async function buildLocalDigest(
- root: string,
- graph: GraphV1 | null,
- opts: { autoApprove?: boolean; fetchImpl?: typeof fetch; knownThreads?: HistoryThread[]; context?: PushContext } = {},
-): Promise<{ digest: RepoDigest; warning?: string } | { error: string }> {
- const ctx = opts.context ?? pushContext(root, opts);
- if (!ctx) {
- return { error: "this directory has no GitHub `origin` remote — graft can only push a GitHub repository today" };
- }
- const { token, fetchImpl } = ctx;
-
- const commits = readCommits(root);
- if (commits.length === 0) {
- return { error: "no commits found here — is this a shallow clone with no history?" };
- }
- const symbols = readSymbols(graph);
-
- let threads: Awaited<ReturnType<typeof readThreads>> = [];
- let warning: string | undefined;
- // The GitHub-side sources start with the threads rather than after them:
- // they are a request or two each, and waiting behind 400 is waiting for no reason.
- const remote = token
- ? Promise.all([
- readBranchProtection(ctx.owner, ctx.name, ctx.branch, token, fetchImpl as never),
- readDeclinedIssues(ctx.owner, ctx.name, token, fetchImpl as never),
- ])
- : Promise.resolve([[], []] as const);
- if (token) {
- try {
- const known = new Map((opts.knownThreads ?? []).map((t) => [t.number, t]));
- threads = await readThreads(ctx.owner, ctx.name, token, fetchImpl as never, undefined, undefined, known, ctx.threads);
- } catch {
- warning = "could not read pull-request discussion; mining commits and repo files only";
- }
- } else {
- warning =
- "no GitHub token found (`gh auth login`, or GH_TOKEN) — mining commits and repo files only, without pull-request discussion";
- }
- const [protection, declined] = await remote;
-
- const sources = budgetSources([
- ...readAgentInstructions(root),
- ...readDecisionDocs(root),
- ...readCodeowners(root),
- ...readCodifiedRules(root),
- ...readReverts(root),
- ...readTestNames(symbols.map((s) => ({ name: s.name, path: s.path }))),
- ...protection,
- ...declined,
- ]);
-
- const digest = buildDigest({
- owner: ctx.owner,
- name: ctx.name,
- headSha: ctx.headSha,
- defaultBranch: ctx.branch,
- isPrivate: await ctx.isPrivate(),
- commits,
- threads,
- symbols,
- sources,
- autoApprove: opts.autoApprove ?? true,
- agents: pickedAgents(root),
- });
- return { digest, warning };
-}
-
-/**
- * Send a digest to the brain and return the job to poll.
- *
- * Chunked and gzipped when the server advertises both, gzipped in one POST when
- * it advertises only gzip, and today's plain POST otherwise.
- */
-export async function pushDigest(
- link: BrainLink,
- digest: RepoDigest,
- fetchImpl: typeof fetch = fetch,
- caps: UploadCaps = {},
- opts: Omit<UploadOptions, "fetchImpl"> = {},
-): Promise<{ jobId: string } | { error: string }> {
- return uploadDigest(link, digest, caps, { ...opts, fetchImpl });
-}
diff --git a/src/brain/signup.ts b/src/brain/signup.ts
deleted file mode 100644
index 648ceb8c..00000000
--- a/src/brain/signup.ts
+++ /dev/null
@@ -1,334 +0,0 @@
-/**
- * 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 --trail <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 trail 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 { brand } from "../brand.js";
-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.
- *
- * Trail's own front end, not the shared `agents.nanonets.com` one that `link.ts`
- * calls for the API. Both are served by the same backend, so either would mint a
- * working token — but this URL is the one a person looks at, and it has to be
- * the Trail-branded build, with Trail's Auth0 redirect behind the signup. */
-const DEFAULT_WEB_BASE_URL = "https://app.trailhq.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.
- *
- * `error` is the sentence printed to the user and `reason` is the same fact as a
- * category. They are separate because the sentence names the repo and the link,
- * so it can never be the thing telemetry reports — and matching on its text to
- * recover the category would put a user-facing string in a position where
- * rewording it silently changes what gets counted.
- */
-export type HandoffFailure = "timed_out" | "bad_callback";
-export type HandoffResult = { link: BrainLink } | { error: string; reason: HandoffFailure };
-
-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 trail is connected. Return to your terminal — the push is already running."
- : "That sign-up doesn't match this terminal. Run graft trail 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: "sign-up came back incomplete · nothing was sent — run graft trail push again", reason: "bad_callback" });
- return;
- }
-
- // 303 so the browser issues a plain GET, and Location built from
- // GRAFT_BRAIN_URL rather than anything the query carried — the same reason
- // the Trail side builds its callback rather than being told one.
- res.writeHead(303, { location: brainUrl(brainId), "cache-control": "no-store" });
- res.end();
- // 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: `no sign-up after ${
- timeoutMs >= 60_000 ? `${Math.round(timeoutMs / 60_000)} minutes` : `${Math.max(1, Math.round(timeoutMs / 1000))} seconds`
- } · nothing was sent — run graft trail push again`,
- reason: "timed_out",
- }),
- 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();
- }
- },
- };
-}
-
-/** The Trail front end this machine is pointed at, without a trailing slash.
- *
- * Read at the moment it is needed rather than captured once, matching the rest
- * of the brain code: GRAFT_BRAIN_URL is free to move between calls. TRAIL_WEB_URL
- * moves only the pages, for a Trail whose pages and API are on different hosts,
- * as a local one is. */
-export function webBaseUrl(baseUrl?: string): string {
- return (process.env.TRAIL_WEB_URL || process.env.GRAFT_BRAIN_URL || baseUrl || DEFAULT_WEB_BASE_URL).replace(/\/+$/, "");
-}
-
-/** Where the browser is sent once the handoff has been accepted.
- *
- * Back into Trail, at the screen that shows the brain being built. The
- * alternative — leaving the person on a local page that says "go back to your
- * terminal" — ends the flow on a blank throwaway served by a port that is about
- * to close, at exactly the moment there is something to watch.
- *
- * NOT `/brain/<id>`, which is where this pointed first. That route redirects to
- * the brain's graph, and the redirect fires the instant the row exists — which
- * is minutes before it has any rules in it. Every terminal signup therefore
- * landed on an empty visualisation of a brain that was, at that moment, being
- * built perfectly well. The build screen is the same wait the browser-first
- * flow shows, and it leads to the graph once there is a graph. */
-export function brainUrl(brainId: string, baseUrl?: string): string {
- return `${webBaseUrl(baseUrl)}/get-started?step=build&brain=${encodeURIComponent(brainId)}`;
-}
-
-/** Where a trail's suggested context-file changes are reviewed and accepted:
- * the Context files overview, which lists every file the repo's agents read
- * (CLAUDE.md, AGENTS.md, Cursor rules, folder files, skills) with what waits
- * on each. Needs a Trail that has the page (NanoNets/assign#2957). */
-export function reviewUrl(brainId: string, baseUrl?: string): string {
- return `${webBaseUrl(baseUrl)}/brain/${encodeURIComponent(brainId)}/context-files`;
-}
-
-/** Where to send the browser for a repo's brain.
- *
- * No port when an agent runs the push: nothing stays listening on loopback, so
- * Trail keeps the trail it made under `state` and graft asks for it by that. */
-export function signupUrl(opts: { repo: string; port?: number; state: string; baseUrl?: string }): string {
- const base = webBaseUrl(opts.baseUrl);
- const q = new URLSearchParams({ step: "repo", graft_repo: opts.repo });
- if (opts.port !== undefined) q.set("graft_port", String(opts.port));
- q.set("graft_state", opts.state);
- // Under trail, signing in shares notes rather than making a brain, and the page says so.
- if (brand() === "trail") q.set("graft_mode", "trail");
- return `${base}/get-started?${q.toString()}`;
-}
-
-/*
- * Signing up when an agent runs the push.
- *
- * Claude Code, Cursor and the rest run `graft trail push` with no terminal, and
- * show the person nothing until the command exits. A loopback listener cannot
- * work there: the link would sit unseen inside a running command, and anything
- * the browser is sent back to is gone by the time the person finishes signing
- * up. So the push runs in two short steps instead. The first opens the sign-up
- * page, saves the state it put in the link, and exits at once so the agent can
- * tell the person what to do. The next asks Trail every couple of seconds,
- * by that state, whether the sign-up has finished, and carries on with the push
- * when it has.
- */
-
-/** A fresh state for a sign-up link: 24 random bytes, which is what Trail
- * accepts and what makes the link impossible to guess. */
-export function newSignupState(): string {
- return randomBytes(24).toString("base64url");
-}
-
-/** How long one agent-run push waits for the sign-up. Under the two minutes an
- * agent gives a command by default, so the wait ends with a message it can read
- * rather than a killed process. */
-export const AGENT_WAIT_MS = 90 * 1000;
-
-/** How often it asks. */
-export const AGENT_POLL_MS = 2000;
-
-/** How long a saved state is worth asking about: a minute under the fifteen
- * Trail keeps an unclaimed sign-up, so graft never waits on one Trail dropped. */
-export const PENDING_SIGNUP_TTL_MS = 14 * 60 * 1000;
-
-/** Why asking stopped short of a link. */
-export type ClaimFailure = "expired" | "unsupported";
-export type ClaimResult = { link: BrainLink } | { pending: true } | { error: string; reason: ClaimFailure };
-
-/**
- * Ask Trail once whether the sign-up for `state` has finished.
- *
- * A network error or a server error counts as "not yet": one bad request in a
- * ninety-second wait is not a reason to give up on it.
- */
-export async function claimSignup(state: string, apiBase: string, fetchImpl: typeof fetch = fetch): Promise<ClaimResult> {
- let res: Response;
- try {
- res = await fetchImpl(`${apiBase}/api/public/graft-handoffs/claim`, {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ state }),
- signal: AbortSignal.timeout(10_000),
- });
- } catch {
- return { pending: true };
- }
- if (res.status === 200) {
- const body = (await res.json().catch(() => ({}))) as { brain_id?: string; token?: string };
- if (body.brain_id && body.token) return { link: { brainId: body.brain_id, token: body.token } };
- return { pending: true };
- }
- await res.body?.cancel().catch(() => undefined);
- if (res.status === 410) {
- return { error: "that sign-up link was already used or has expired · run graft trail push again for a new one", reason: "expired" };
- }
- // An older Trail, without the route. Waiting on it would never end.
- if (res.status === 404 || res.status === 405) {
- return {
- error: "this Trail can't hand a sign-up to an agent yet · run graft trail push in a terminal, or graft trail connect <trailId>:<token>",
- reason: "unsupported",
- };
- }
- return { pending: true };
-}
-
-/** Ask until the sign-up finishes, Trail says it never will, or `timeoutMs`
- * passes — which comes back as `{ pending: true }`. */
-export async function waitForSignup(
- state: string,
- apiBase: string,
- opts: { timeoutMs?: number; intervalMs?: number; fetchImpl?: typeof fetch } = {},
-): Promise<ClaimResult> {
- const deadline = Date.now() + (opts.timeoutMs ?? AGENT_WAIT_MS);
- const interval = opts.intervalMs ?? AGENT_POLL_MS;
- for (;;) {
- const got = await claimSignup(state, apiBase, opts.fetchImpl);
- if (!("pending" in got)) return got;
- if (Date.now() + interval > deadline) return got;
- await new Promise((r) => setTimeout(r, interval));
- }
-}
-
-/** 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/brain/upload.ts b/src/brain/upload.ts
deleted file mode 100644
index b9fc70df..00000000
--- a/src/brain/upload.ts
+++ /dev/null
@@ -1,254 +0,0 @@
-/**
- * Getting a digest to Trail quickly, and getting it there at all.
- *
- * A busy repository's digest is several megabytes of JSON — a thousand commit
- * messages, two hundred threads of discussion, four thousand symbols — and it
- * used to go up as one uncompressed POST with no retry. On a hotel connection
- * that is a minute of upload and one dropped packet from starting over.
- *
- * JSON compresses about tenfold, so the body is gzipped whenever the server
- * says it takes gzip. When it also says it takes chunked uploads, the gzip is
- * cut into 1 MiB pieces and sent four at a time, each retried on its own: a
- * blip costs one chunk, not the push. Against an older Trail neither flag is
- * set and the upload is exactly the single POST it always was.
- */
-import { gzip as gzipCb } from "node:zlib";
-import { promisify } from "node:util";
-import type { RepoDigest } from "../app/history.js";
-import { baseUrlFor, type BrainLink } from "./link.js";
-
-const gzipAsync = promisify(gzipCb);
-
-/** The size of one chunk: the index-th slice of the gzip is bytes [i*CHUNK, (i+1)*CHUNK). */
-export const CHUNK_BYTES = 1024 * 1024;
-/** Chunks in flight at once. */
-export const CHUNK_CONCURRENCY = 4;
-/** Waits before each retry. Four retries, so five attempts in all. */
-export const RETRY_DELAYS_MS = [500, 1000, 2000, 4000] as const;
-
-/** What the server said it accepts, from GET /repo. */
-export interface UploadCaps {
- /** `gzip_upload: true` — POST /repo takes `Content-Encoding: gzip`. */
- gzip?: boolean;
- /** `chunked_upload: true` — the /repo/uploads routes exist. */
- chunked?: boolean;
-}
-
-export interface UploadOptions {
- fetchImpl?: typeof fetch;
- sleep?: (ms: number) => Promise<void>;
- chunkBytes?: number;
- concurrency?: number;
-}
-
-export type UploadResult = { jobId: string } | { error: string };
-
-const realSleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
-
-/** The digest as the exact bytes a single POST would carry, gzipped. */
-export async function gzipDigest(digest: RepoDigest): Promise<Buffer> {
- return gzipAsync(Buffer.from(JSON.stringify(digest), "utf8"));
-}
-
-/** Retry on what a retry can fix: the network, the server, the rate limit. */
-function retryable(status: number): boolean {
- return status >= 500 || status === 429;
-}
-
-/**
- * One request, retried with backoff on network errors, 5xx and 429.
- *
- * Returns the last response when retries run out on a status (so the caller
- * can print the server's own words), or throws the last network error.
- */
-async function withRetry(
- send: () => Promise<Response>,
- sleep: (ms: number) => Promise<void>,
-): Promise<{ res: Response; attempts: number; sawNetworkError: boolean }> {
- let sawNetworkError = false;
- let lastError: unknown;
- for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt++) {
- if (attempt > 0) await sleep(RETRY_DELAYS_MS[attempt - 1]!);
- try {
- const res = await send();
- if (!retryable(res.status) || attempt === RETRY_DELAYS_MS.length) {
- return { res, attempts: attempt + 1, sawNetworkError };
- }
- // Drain it so the connection is released before the next attempt.
- await res.arrayBuffer().catch(() => undefined);
- } catch (e) {
- sawNetworkError = true;
- lastError = e;
- }
- }
- throw lastError instanceof Error ? lastError : new Error(String(lastError));
-}
-
-function authHeaders(link: BrainLink, extra: Record<string, string> = {}): Record<string, string> {
- return { authorization: `Bearer ${link.token}`, accept: "application/json", ...extra };
-}
-
-/** Today's response to an ingest, read the same way for every route that returns it. */
-async function ingestResult(res: Response): Promise<UploadResult> {
- const text = await res.text();
- if (!res.ok) return { error: `Trail refused the upload: ${res.status} ${text.slice(0, 200)}` };
- try {
- return { jobId: String((JSON.parse(text) as { job_id?: string }).job_id ?? "") };
- } catch {
- return { jobId: "" };
- }
-}
-
-/**
- * The single POST to /repo — gzipped when the server takes it, plain otherwise.
- * Not retried: a repeated POST of a whole ingest is not idempotent, and a 409
- * for "already running" on the retry would read as a refusal.
- */
-export async function postDigestOnce(
- link: BrainLink,
- digest: RepoDigest,
- opts: { gzip?: boolean; fetchImpl?: typeof fetch; query?: string; timeoutMs?: number } = {},
-): Promise<Response> {
- const fetchImpl = opts.fetchImpl ?? fetch;
- const url = `${baseUrlFor(link)}/api/public/brains/${encodeURIComponent(link.brainId)}/repo${opts.query ?? ""}`;
- const json = JSON.stringify(digest);
- const body = opts.gzip ? await gzipAsync(Buffer.from(json, "utf8")) : json;
- const headers = authHeaders(link, { "content-type": "application/json" });
- if (opts.gzip) headers["content-encoding"] = "gzip";
- return fetchImpl(url, {
- method: "POST",
- headers,
- body: body as unknown as RequestInit["body"],
- ...(opts.timeoutMs ? { signal: AbortSignal.timeout(opts.timeoutMs) } : {}),
- });
-}
-
-/**
- * Upload the full digest by whichever route the server advertises.
- *
- * Chunked when `caps.chunked`; if the upload session cannot even be opened
- * (a 404 from a server that advertised the flag but not the route), it falls
- * back to the single POST rather than failing a push that would otherwise work.
- */
-export async function uploadDigest(
- link: BrainLink,
- digest: RepoDigest,
- caps: UploadCaps,
- opts: UploadOptions = {},
-): Promise<UploadResult> {
- if (caps.chunked) {
- const chunked = await uploadChunked(link, digest, opts);
- if (!("fallback" in chunked)) return chunked;
- }
- try {
- return await ingestResult(await postDigestOnce(link, digest, { gzip: caps.gzip, fetchImpl: opts.fetchImpl }));
- } catch (e) {
- return { error: `could not reach Trail: ${e instanceof Error ? e.message : e}` };
- }
-}
-
-/**
- * The chunked route:
- *
- * POST /repo/uploads {stage, auto_approve, chunks, bytes} → {upload_id}
- * PUT /repo/uploads/:id/chunks/:index raw gzip slice, idempotent → 204
- * POST /repo/uploads/:id/complete → today's /repo response
- *
- * `{fallback: true}` means the session could not be opened and nothing was
- * sent, so the caller may use the single POST instead.
- */
-export async function uploadChunked(
- link: BrainLink,
- digest: RepoDigest,
- opts: UploadOptions = {},
-): Promise<UploadResult | { fallback: true }> {
- const fetchImpl = opts.fetchImpl ?? fetch;
- const sleep = opts.sleep ?? realSleep;
- const chunkBytes = opts.chunkBytes ?? CHUNK_BYTES;
- const base = `${baseUrlFor(link)}/api/public/brains/${encodeURIComponent(link.brainId)}/repo/uploads`;
-
- const gz = await gzipDigest(digest);
- const chunks = Math.max(1, Math.ceil(gz.length / chunkBytes));
-
- let uploadId = "";
- try {
- const { res } = await withRetry(
- () =>
- fetchImpl(base, {
- method: "POST",
- headers: authHeaders(link, { "content-type": "application/json" }),
- body: JSON.stringify({ stage: "full", auto_approve: digest.auto_approve, chunks, bytes: gz.length }),
- }),
- sleep,
- );
- const text = await res.text();
- if (res.status === 404 || res.status === 405) return { fallback: true };
- if (!res.ok) {
- // 409 is the one refusal worth passing on as-is: an ingest is already
- // running, and a single POST would be told the same.
- if (res.status === 409) return { error: `Trail refused the upload: ${res.status} ${text.slice(0, 200)}` };
- return { fallback: true };
- }
- uploadId = String((JSON.parse(text) as { upload_id?: string }).upload_id ?? "");
- } catch {
- return { fallback: true };
- }
- if (!uploadId) return { fallback: true };
-
- // Chunks, four at a time, each retried on its own.
- const concurrency = Math.max(1, opts.concurrency ?? CHUNK_CONCURRENCY);
- let next = 0;
- let failure: string | null = null;
- const worker = async () => {
- for (;;) {
- if (failure) return;
- const i = next++;
- if (i >= chunks) return;
- const slice = gz.subarray(i * chunkBytes, Math.min(gz.length, (i + 1) * chunkBytes));
- try {
- const { res } = await withRetry(
- () =>
- fetchImpl(`${base}/${encodeURIComponent(uploadId)}/chunks/${i}`, {
- method: "PUT",
- headers: authHeaders(link, { "content-type": "application/octet-stream" }),
- body: slice as unknown as RequestInit["body"],
- }),
- sleep,
- );
- if (!res.ok) {
- const text = await res.text().catch(() => "");
- failure = `Trail refused part ${i + 1} of ${chunks}: ${res.status} ${text.slice(0, 200)}`;
- return;
- }
- await res.arrayBuffer().catch(() => undefined);
- } catch (e) {
- failure = `could not send part ${i + 1} of ${chunks} to Trail: ${e instanceof Error ? e.message : e}`;
- return;
- }
- }
- };
- await Promise.all(Array.from({ length: Math.min(concurrency, chunks) }, worker));
- if (failure) return { error: failure };
-
- try {
- const { res, sawNetworkError } = await withRetry(
- () =>
- fetchImpl(`${base}/${encodeURIComponent(uploadId)}/complete`, {
- method: "POST",
- headers: authHeaders(link, { "content-type": "application/json" }),
- body: "{}",
- }),
- sleep,
- );
- // A complete that was lost on the way back may have started the ingest, so
- // its retry being told "already running" means it worked. The watcher that
- // follows reads the build either way.
- if (res.status === 409 && sawNetworkError) {
- await res.arrayBuffer().catch(() => undefined);
- return { jobId: "" };
- }
- return await ingestResult(res);
- } catch (e) {
- return { error: `could not reach Trail to finish the upload: ${e instanceof Error ? e.message : e}` };
- }
-}
diff --git a/src/brain/watch-trail.ts b/src/brain/watch-trail.ts
deleted file mode 100644
index 2ce2c45a..00000000
--- a/src/brain/watch-trail.ts
+++ /dev/null
@@ -1,394 +0,0 @@
-/**
- * `graft trail watch`: wait until Trail has something for this repo, then say so
- * once.
- *
- * Trail suggests changes to a repository's CLAUDE.md and its other context files
- * while it reads the history, and a person reviews and accepts them in the
- * browser. Until now the only way for a coding agent to notice either was a loop
- * the agent wrote for itself — a setup prompt told Claude to save a
- * `graft-watcher.sh` that ran `graft trail pull --dry-run` every minute and
- * grepped the text. That loop parsed sentences written for people, broke on
- * every rewording, and printed a screenful per tick into a session that only
- * ever needed one line at the end.
- *
- * So this is that loop, done properly: it reads the same numbers the dry run
- * prints by calling the functions the pull itself is built on (`gatherPull`),
- * stays silent while nothing has changed, and ends with ONE block an agent can
- * relay as it stands — suggestions are waiting for review, accepted changes are
- * ready to pull, or it gave up waiting. `--json` is the same block for a script.
- *
- * The same read, capped at a few seconds, is what the session-start hook uses
- * to mention a trail that has something waiting (see `trailContextLine`).
- */
-import type { BrainLink } from "./link.js";
-import { gatherPull, type Gathered } from "./pull.js";
-import { reviewUrl } from "./signup.js";
-import { countBucket, durationBucket, type TRAIL_WATCH_REASONS } from "../telemetry/contract.js";
-import { track } from "../telemetry/track.js";
-
-/** One accepted change's file, and the sections it touches. */
-export interface PendingFile {
- /** Repo-relative, forward slashes. */
- path: string;
- /** The headings of the sections the changes edit or add, in order, once
- * each. Empty for a change that carries the whole file (a new Cursor rule,
- * a skill), which has no section to name. */
- headings: string[];
-}
-
-/** What Trail holds for this checkout at one moment. */
-export interface TrailSnapshot {
- /** Suggestions for the wired agents' files, every one Trail has made. Null
- * when the counts could not be read this time. */
- suggested: number | null;
- /** Accepted changes a pull would still have to write: Trail's accepted list,
- * less whatever is already in the files here. */
- accepted: number;
- /** The files those accepted changes land in. */
- files: PendingFile[];
- /** The accepted changes' ids, sorted — what "has not changed" is judged on,
- * so one change accepted and another un-accepted in the same minute is still
- * a change even though the count held. */
- ids: string[];
- reviewUrl: string;
-}
-
-export type SnapshotResult =
- | { ok: true; snapshot: TrailSnapshot }
- | {
- ok: false;
- error: string;
- /** True when waiting cannot help: Trail answered and refused (a revoked
- * or wrong token). False for anything the next tick may not hit. */
- fatal: boolean;
- };
-
-/**
- * The accepted changes a pull would still write, file by file, out of a planned
- * pull. Changes already in the file are left out: the pull only tells Trail
- * about those, so they are nothing to wait for. Changes the pull would skip (the
- * file moved on since Trail read it) stay in — they are accepted and not
- * written, and the pull is where someone hears why.
- */
-export function pendingFrom(g: Gathered): { accepted: number; files: PendingFile[]; ids: string[] } {
- const files: PendingFile[] = [];
- const ids: string[] = [];
- for (const { plan } of g.planned) {
- const changes = [...plan.written, ...plan.skipped.map((s) => s.change)];
- if (changes.length === 0) continue;
- const headings: string[] = [];
- for (const c of changes) {
- ids.push(c.id);
- const h = (c.kind === "edit" || c.kind === "add") && c.heading ? c.heading.trim() : "";
- if (h && !headings.includes(h)) headings.push(h);
- }
- // Two entries for one path (the root CLAUDE.md is fetched on its own route)
- // are one file to a reader.
- const same = files.find((f) => f.path === plan.path);
- if (!same) files.push({ path: plan.path, headings });
- else for (const h of headings) if (!same.headings.includes(h)) same.headings.push(h);
- }
- return { accepted: ids.length, files, ids: ids.sort() };
-}
-
-/** 401 and 403 are a token Trail no longer takes; nothing else is final. */
-const FATAL_STATUS = new Set([401, 403]);
-
-/**
- * One read of what Trail holds for this checkout. Never throws: every failure
- * comes back as a result, marked fatal only when waiting cannot fix it.
- */
-export async function readTrailSnapshot(
- repo: string,
- link: BrainLink,
- wired: string[],
- fetchImpl: typeof fetch = fetch,
-): Promise<SnapshotResult> {
- try {
- const g = await gatherPull(repo, link, wired, fetchImpl);
- if (g.errors.length > 0) {
- return {
- ok: false,
- error: g.errors.map((e) => e.message).join("; "),
- fatal: g.errors.some((e) => e.status !== undefined && FATAL_STATUS.has(e.status)),
- };
- }
- const pending = pendingFrom(g);
- return {
- ok: true,
- snapshot: { suggested: g.suggested ? g.suggested.count : null, ...pending, reviewUrl: reviewUrl(link.brainId) },
- };
- } catch (e) {
- return { ok: false, error: `could not read the trail: ${e instanceof Error ? e.message : e}`, fatal: false };
- }
-}
-
-/* -------------------------------------------------------------------------- */
-/* the watch */
-/* -------------------------------------------------------------------------- */
-
-/**
- * Why the watch ended. `suggestions`: there are suggestions and none accepted —
- * someone has reviewing to do. `accepted`: accepted changes, holding still.
- * `timeout`: neither, after `--timeout`. `refused`: Trail turned the token
- * away. `no_trail`: nothing attached to watch.
- */
-export type WatchExitReason = (typeof TRAIL_WATCH_REASONS)[number];
-
-export interface WatchTrailResult {
- reason: WatchExitReason;
- /** Last known counts; null suggested when they were never read. */
- suggested: number | null;
- accepted: number;
- files: PendingFile[];
- reviewUrl: string;
- waitedMs: number;
- /** For `refused`: Trail's own words. */
- error?: string;
- /** False when not one read succeeded, so a timeout can say it never got through. */
- everRead: boolean;
-}
-
-export interface WatchTrailOptions {
- wired: string[];
- /** Between reads. Default a minute: Trail's build adds suggestions over
- * minutes and a person reviews them over longer, so anything shorter is
- * requests nobody is waiting on. */
- intervalMs?: number;
- /** How long the accepted set must hold still before it is reported. Someone
- * accepting changes one at a time is mid-review; reporting the first would
- * send the agent off to pull while they are still clicking. */
- settleMs?: number;
- timeoutMs?: number;
- /** Keep waiting while suggestions are only waiting for review. */
- acceptedOnly?: boolean;
- fetchImpl?: typeof fetch;
- now?: () => number;
- sleep?: (ms: number) => Promise<void>;
- /** Every read, for `--verbose`. */
- onTick?: (r: SnapshotResult) => void;
-}
-
-export const WATCH_DEFAULTS = { intervalMs: 10_000, settleMs: 10_000, timeoutMs: 60 * 60_000 } as const;
-
-/**
- * Read Trail every interval until one of three things is true, and return which.
- *
- * - Suggestions and nothing accepted (unless `acceptedOnly`): the person has
- * reviewing to do, and saying so now is the point — waiting on them to
- * accept something first would hold the agent for as long as they take.
- * - Accepted changes that have not changed for `settleMs`.
- * - `timeoutMs` passed.
- *
- * A read that fails for a reason the next one may not hit (the network, a 5xx)
- * is simply retried on the next tick; only a refused token ends the watch early.
- */
-export async function watchTrail(repo: string, link: BrainLink, opts: WatchTrailOptions): Promise<WatchTrailResult> {
- const intervalMs = opts.intervalMs ?? WATCH_DEFAULTS.intervalMs;
- const settleMs = opts.settleMs ?? WATCH_DEFAULTS.settleMs;
- const timeoutMs = opts.timeoutMs ?? WATCH_DEFAULTS.timeoutMs;
- const now = opts.now ?? Date.now;
- // Not unref'd: between reads this timer is the only thing the process is
- // waiting on, and an unref'd one would let it exit mid-watch with nothing
- // printed — the same trap watch.ts documents for the build watcher.
- const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
- // Every request carries X-Graft-Watch, which is how Trail knows something is
- // watching this trail right now and can tell the page that Claude Code will
- // ask before pulling, instead of telling the person to run the pull. A manual
- // pull and the session-start check do not send it.
- const fetchImpl = withWatchHeader(opts.fetchImpl ?? fetch);
-
- const startedAt = now();
- const deadline = startedAt + timeoutMs;
- let last: TrailSnapshot | null = null;
- let lastSuggested: number | null = null;
- // The accepted set as last seen, and since when it has looked like that.
- let heldKey: string | null = null;
- let heldSince = startedAt;
-
- const result = (reason: WatchExitReason, extra: Partial<WatchTrailResult> = {}): WatchTrailResult => ({
- reason,
- suggested: lastSuggested,
- accepted: last?.accepted ?? 0,
- files: last?.files ?? [],
- reviewUrl: reviewUrl(link.brainId),
- waitedMs: now() - startedAt,
- everRead: last !== null,
- ...extra,
- });
-
- for (;;) {
- const r = await readTrailSnapshot(repo, link, opts.wired, fetchImpl);
- opts.onTick?.(r);
- let wakeAt = now() + intervalMs;
- if (r.ok) {
- const s = r.snapshot;
- last = s;
- // A counts request that failed this time is not "no suggestions": keep
- // the last number rather than let one blip read as zero.
- if (s.suggested !== null) lastSuggested = s.suggested;
- const key = s.ids.join("\n");
- if (key !== heldKey) {
- heldKey = key;
- heldSince = now();
- }
- if (s.accepted > 0) {
- if (now() - heldSince >= settleMs) return result("accepted");
- // Wake when the set would have settled, not a whole interval later.
- wakeAt = Math.min(wakeAt, heldSince + settleMs);
- } else if (!opts.acceptedOnly && (s.suggested ?? 0) > 0) {
- return result("suggestions");
- }
- } else if (r.fatal) {
- return result("refused", { error: r.error });
- }
- if (now() >= deadline) return result("timeout");
- await sleep(Math.max(0, Math.min(wakeAt, deadline) - now()));
- }
-}
-
-/* -------------------------------------------------------------------------- */
-/* what it says */
-/* -------------------------------------------------------------------------- */
-
-const fmt = (n: number) => n.toLocaleString("en-US");
-const plural = (n: number, one: string, many: string) => (n === 1 ? one : many);
-
-/** `CLAUDE.md (Commands, Testing), web/CLAUDE.md (SEO metadata)`. */
-export function filesSummary(files: PendingFile[]): string {
- return files.map((f) => (f.headings.length ? `${f.path} (${f.headings.join(", ")})` : f.path)).join(", ");
-}
-
-/** `60 minutes`, `1 minute`, `30 seconds`. */
-function span(ms: number): string {
- if (ms >= 60_000) {
- const m = Math.round(ms / 60_000);
- return `${m} ${plural(m, "minute", "minutes")}`;
- }
- const s = Math.max(1, Math.round(ms / 1000));
- return `${s} ${plural(s, "second", "seconds")}`;
-}
-
-/**
- * The one block the watch prints when it ends — written to be relayed as it
- * stands, so every ending names the next step.
- *
- * `timeoutMs` is the configured timeout, which is what "still waiting after"
- * should say rather than the few seconds past it the last read took.
- */
-export function watchExitLines(r: WatchTrailResult, timeoutMs: number): string[] {
- switch (r.reason) {
- case "suggestions": {
- const n = r.suggested ?? 0;
- return [`● ${fmt(n)} ${plural(n, "suggestion is", "suggestions are")} waiting for review`, ` review: ${r.reviewUrl}`];
- }
- case "accepted": {
- const where = filesSummary(r.files);
- return [
- `✓ ${fmt(r.accepted)} accepted ${plural(r.accepted, "change is", "changes are")} ready${where ? `: ${where}` : ""}`,
- ` run graft trail pull to write ${plural(r.accepted, "it", "them")}`,
- ];
- }
- case "timeout": {
- if (!r.everRead) return [`· still waiting after ${span(timeoutMs)}: could not reach Trail`];
- const lines = [`· still waiting after ${span(timeoutMs)}: ${fmt(r.suggested ?? 0)} suggested, ${fmt(r.accepted)} accepted`];
- if ((r.suggested ?? 0) > 0) lines.push(` review: ${r.reviewUrl}`);
- return lines;
- }
- case "refused":
- return [`✗ ${r.error ?? "Trail refused the request"}`, " the trail's token may have been revoked — attach it again with graft trail connect"];
- case "no_trail":
- return ["✗ this repo has no trail yet — run graft trail push first"];
- }
-}
-
-/** The same ending, for a script. Counts are exact here: this goes to the
- * caller's own terminal, not over the wire. */
-export function watchExitJson(r: WatchTrailResult): Record<string, unknown> {
- return {
- reason: r.reason,
- suggested: r.suggested,
- accepted: r.accepted,
- files: r.files,
- review_url: r.reason === "no_trail" ? null : r.reviewUrl,
- waited_s: Math.round(r.waitedMs / 1000),
- ...(r.error ? { error: r.error } : {}),
- };
-}
-
-/** Exit code: 0 when there is something to act on, 2 for a timeout (distinct,
- * so a script can tell "nothing yet" from "broken"), 1 for everything else. */
-export function watchExitCode(r: WatchTrailResult): number {
- if (r.reason === "suggestions" || r.reason === "accepted") return 0;
- if (r.reason === "timeout") return 2;
- return 1;
-}
-
-/**
- * The `trail_watch_exit` event. Counts as buckets and the reason as a member of
- * a fixed set, like every other event — see TELEMETRY.md.
- */
-export function trackWatchExit(repo: string, r: WatchTrailResult): void {
- track(
- "trail_watch_exit",
- {
- reason: r.reason,
- suggested_bucket: countBucket(r.suggested ?? 0),
- accepted_bucket: countBucket(r.accepted),
- duration_bucket: durationBucket(r.waitedMs),
- },
- { repo },
- );
-}
-
-/* -------------------------------------------------------------------------- */
-/* the session-start line */
-/* -------------------------------------------------------------------------- */
-
-/** `CLAUDE.md: Commands, Testing; web/CLAUDE.md: SEO metadata` — the inline
- * form, which sits inside parentheses in a sentence. */
-function filesInline(files: PendingFile[]): string {
- return files.map((f) => (f.headings.length ? `${f.path}: ${f.headings.join(", ")}` : f.path)).join("; ");
-}
-
-/**
- * The line the session-start hook adds when the trail has something waiting,
- * or null when it has nothing worth a session's attention. Addressed to the
- * agent, which is who reads a hook's context: what is waiting, and what to ask
- * the person.
- *
- * Accepted changes are always mentioned: they are one command away from done,
- * and they stop being mentioned the moment that command runs.
- *
- * Suggestions are not like that. Trail's count is every suggestion it has ever
- * made for these files, whatever became of it, so it only ever grows — and a
- * line repeating "12 suggestions are waiting" at the start of every session,
- * long after all twelve were reviewed, is a nag the agent learns to ignore
- * along with everything else in the opening context. So suggestions are
- * mentioned only when the count has grown past `lastSeen`, the count this
- * repo's hook saw the time before, and then only the difference. With no count
- * seen before, they are mentioned once, in full.
- */
-export function trailContextLine(s: TrailSnapshot, lastSeen?: number): string | null {
- if (s.accepted > 0) {
- const where = filesInline(s.files);
- return `Trail: ${fmt(s.accepted)} accepted ${plural(s.accepted, "change is", "changes are")} waiting${where ? ` (${where})` : ""}. Ask the user whether to run graft trail pull.`;
- }
- const n = s.suggested ?? 0;
- if (n <= 0) return null;
- if (lastSeen === undefined) {
- return `Trail: ${fmt(n)} ${plural(n, "suggestion is", "suggestions are")} waiting for review at ${s.reviewUrl}.`;
- }
- const d = n - lastSeen;
- if (d <= 0) return null;
- return `Trail: ${fmt(d)} new ${plural(d, "suggestion since your last session is", "suggestions since your last session are")} waiting for review at ${s.reviewUrl}.`;
-}
-
-/** `fetch` with X-Graft-Watch: 1 added to every request's headers. */
-export function withWatchHeader(inner: typeof fetch): typeof fetch {
- return ((input: Parameters<typeof fetch>[0], init?: RequestInit) => {
- const headers = new Headers(init?.headers);
- headers.set("x-graft-watch", "1");
- return inner(input, { ...init, headers });
- }) as typeof fetch;
-}
diff --git a/src/brain/watch.ts b/src/brain/watch.ts
deleted file mode 100644
index eaf072b2..00000000
--- a/src/brain/watch.ts
+++ /dev/null
@@ -1,528 +0,0 @@
-/**
- * Watching a brain being built, from the terminal.
- *
- * `graft trail push` used to end at "it is being mined into rules now — a few
- * minutes. Watch it finish in your browser." and hand the prompt straight back.
- * That sentence is the last thing this process ever says about the work, and it
- * is said BEFORE the part that actually fails: of the repo brains attempted in
- * production, roughly a third die inside the miner, after the push succeeded.
- * The terminal has already returned by then, so on this side the failure does
- * not exist at all — and on a CI runner or over SSH, where nobody is going to
- * open a browser, it exists nowhere.
- *
- * So the push now holds the line and reports the same four stages the browser
- * shows, off the same row. Ctrl-C detaches without cancelling anything, because
- * the work is server-side and killing a watcher must never look like killing
- * the build.
- *
- * What it holds the line UNTIL changed with slicing. The history is now mined in
- * several calls rather than one, and the first of them returns in about ten
- * seconds; filing all of the rules into the graph takes minutes more. Mining is
- * where the failures are — the thing this watcher exists to report — and filing
- * is long, dull and reliable, so the line is held through the first and handed
- * back before the second. Holding a terminal through five minutes of successful
- * filing buys nobody anything, and on a CI runner it is five minutes of a job
- * sitting idle.
- */
-import type { BrainLink } from "./link.js";
-import { baseUrlFor } from "./link.js";
-
-/** The stages, in the order they happen. The wording matches Trail's build
- * screen deliberately: two products describing one process differently is how
- * a person ends up unsure whether they are looking at the same thing. */
-export const STAGES = [
- { id: "reach", label: "reaching the repository" },
- { id: "read", label: "reading its history" },
- { id: "mine", label: "mining the rules" },
- { id: "file", label: "filing them into the brain" },
-] as const;
-
-export type StageId = (typeof STAGES)[number]["id"];
-export type StageState = "waiting" | "doing" | "done" | "failed";
-
-export interface Stage {
- id: StageId;
- label: string;
- state: StageState;
- /** A count worth printing beside a stage that has produced one. */
- detail?: string;
-}
-
-/** The repo row, as the public endpoint returns it. Only the fields the stages
- * read, so a field added server-side cannot quietly change what is printed. */
-export interface RepoState {
- status: string;
- errorMessage?: string;
- ruleCount: number;
- commitCount: number;
- threadCount: number;
- /** Rules in the graph right now, from the job still running. The row's own
- * `ruleCount` is only written when that job finishes, so mid-build it is
- * zero however many rules are already there.
- *
- * Optional because an older Trail does not send it, and a graft pointed at
- * one must fall back to waiting for the finished row rather than reading a
- * missing field as "no rules". */
- filedSoFar?: number;
- /** Rules the miner has handed over so far. Grows with every slice of the
- * history that comes back, so it is a floor and never a total. */
- foundSoFar?: number;
- /** Suggested changes to the repo's context files, when Trail sends them. */
- suggestions?: Suggestions;
-}
-
-/**
- * The suggestions Trail has for this repository's context files so far.
- *
- * Counts, because that is all the terminal prints; the changes themselves are
- * reviewed in Trail and written by `graft trail pull`.
- */
-export interface Suggestions {
- /** Changes suggested for the root CLAUDE.md. */
- claudeMd: number;
- /** Changes suggested for every other context file, all kinds together. */
- contextFiles: number;
- /** Per file, when Trail lists them — which is what lets the count be cut to
- * the files the wired agents actually read. */
- files?: Array<{ kind: string; path: string; changes: number }>;
-}
-
-export interface BuildView {
- stages: Stage[];
- /**
- * True once rules are in the graph — which is when this watcher has nothing
- * left to report, not when the job ends. The rest of the slices keep mining
- * and filing after the prompt comes back.
- */
- ready: boolean;
- done: boolean;
- /** The server's own words, when it failed. */
- error: string | null;
-}
-
-const num = (v: unknown): number => (typeof v === "number" && v > 0 ? v : 0);
-
-/**
- * Which stage the work is in.
- *
- * The rule that matters is where a failure lands. A row that never left
- * `pending` failed at the access check; one that read 412 commits and then died
- * failed in the miner. Reporting both as "could not reach it" would send someone
- * to fix repository access for a problem that has nothing to do with it.
- */
-export function stagesFrom(repo: RepoState | null): BuildView {
- const commits = num(repo?.commitCount);
- const threads = num(repo?.threadCount);
- const rules = num(repo?.ruleCount);
-
- const filedSoFar = num(repo?.filedSoFar);
- const foundSoFar = num(repo?.foundSoFar);
-
- const reached = !!repo && repo.status !== "pending";
- const readIt = commits > 0 || threads > 0;
- // Rules that exist, whether the job has finished writing its count or not.
- const hasRules = filedSoFar > 0 || rules > 0;
- const filed = rules > 0;
- const failed = repo?.status === "failed";
-
- const failedAt: StageId | null = !failed ? null : !reached || !readIt ? "reach" : !hasRules ? "mine" : "file";
-
- const order = STAGES.map((s) => s.id);
- const state = (id: StageId): StageState => {
- if (failedAt === id) return "failed";
- if (failedAt && order.indexOf(id) > order.indexOf(failedAt)) return "waiting";
- switch (id) {
- case "reach":
- return reached ? "done" : "doing";
- case "read":
- return readIt ? "done" : reached ? "doing" : "waiting";
- case "mine":
- // Done on the first slice's rules. The remaining slices are still being
- // mined at this point, behind the prompt this watcher is about to
- // return — which is the whole change.
- return hasRules ? "done" : readIt ? "doing" : "waiting";
- case "file":
- return filed ? "done" : hasRules ? "doing" : readIt ? "waiting" : "waiting";
- }
- };
-
- const detail = (id: StageId): string | undefined => {
- if (id === "read" && (commits || threads)) {
- return [commits ? `${commits} commits` : null, threads ? `${threads} discussions` : null].filter(Boolean).join(", ");
- }
- // "so far" because the count grows with each slice that lands. Printing it
- // as a total would promise history that has not been read yet.
- if (id === "mine" && foundSoFar) return `${foundSoFar} rules so far`;
- if (id === "file" && rules) return `${rules} rules`;
- if (id === "file" && filedSoFar) return `${filedSoFar} rules so far`;
- return undefined;
- };
-
- return {
- stages: STAGES.map((s) => ({ id: s.id, label: s.label, state: state(s.id), detail: detail(s.id) })),
- ready: hasRules && !failed,
- done: repo?.status === "completed" && filed,
- error: failed ? (repo?.errorMessage?.trim() || "the read stopped before it finished") : null,
- };
-}
-
-/** A count from a field Trail may send as a number or as the list itself. */
-const countOf = (v: unknown): number => (Array.isArray(v) ? v.length : num(v));
-
-/** The fields of an expected-repo body the watcher reads, as Trail sends them. */
-interface RepoBody {
- repo?: { status?: string; error_message?: string; rule_count?: number; commit_count?: number; thread_count?: number } | null;
- // Absent on an older API, which is why every read of it defaults to zero:
- // a graft that cannot see the in-flight counts falls back to waiting for
- // the finished row, exactly as it did before.
- build?: { found_so_far?: number; filed_so_far?: number } | null;
- claude_md?: { status?: string; quick_ready?: boolean; full_ready?: boolean; changes?: unknown } | null;
- // An object on every SSE frame. On the polled GET it is the `true` that says
- // the routes exist, and the counts ride in `context_files_progress` instead.
- context_files?: { files?: unknown; changes?: unknown } | boolean | null;
- context_files_progress?: { files?: unknown; changes?: unknown } | null;
-}
-
-/**
- * The repo state out of an expected-repo body — the polled GET and every SSE
- * `progress` event carry the same shape. Null when there is no repo row.
- */
-export function parseRepoBody(body: unknown): RepoState | null {
- const b = (body ?? {}) as RepoBody;
- if (!b.repo || typeof b.repo !== "object") return null;
- const state: RepoState = {
- status: String(b.repo.status ?? ""),
- errorMessage: b.repo.error_message,
- ruleCount: num(b.repo.rule_count),
- commitCount: num(b.repo.commit_count),
- threadCount: num(b.repo.thread_count),
- filedSoFar: num(b.build?.filed_so_far),
- foundSoFar: num(b.build?.found_so_far),
- };
- const cf = b.context_files && typeof b.context_files === "object" ? b.context_files : b.context_files_progress;
- if (b.claude_md || cf) {
- const files = Array.isArray(cf?.files)
- ? (cf!.files as Array<{ kind?: unknown; path?: unknown; changes?: unknown }>)
- .filter((f) => f && typeof f === "object")
- .map((f) => ({ kind: String(f.kind ?? ""), path: String(f.path ?? ""), changes: countOf(f.changes) }))
- : undefined;
- state.suggestions = {
- claudeMd: countOf(b.claude_md?.changes),
- contextFiles: cf?.changes !== undefined ? countOf(cf.changes) : (files ?? []).reduce((n, f) => n + f.changes, 0),
- ...(files ? { files } : {}),
- };
- }
- return state;
-}
-
-/**
- * Read the repo row this brain is building.
- *
- * The same endpoint `fetchExpectedRepo` uses, read for its counts rather than
- * its slug. Null on any failure, so a watcher that cannot reach the API prints
- * nothing new rather than inventing a failure the build did not have.
- */
-export async function fetchRepoState(link: BrainLink, fetchImpl: typeof fetch = fetch): Promise<RepoState | null> {
- try {
- const res = await fetchImpl(`${baseUrlFor(link)}/api/public/brains/${encodeURIComponent(link.brainId)}/repo`, {
- headers: { authorization: `Bearer ${link.token}`, accept: "application/json" },
- signal: AbortSignal.timeout(5000),
- });
- if (!res.ok) return null;
- return parseRepoBody(await res.json());
- } catch {
- return null;
- }
-}
-
-/** Past tense, for the no-TTY log: each line reports a stage that finished. */
-const DONE_LABEL: Record<StageId, string> = {
- reach: "reached the repository",
- read: "read its history",
- mine: "mined the rules",
- file: "filed them into the trail",
-};
-
-/** What the spinner says while a stage is running. */
-export const DOING_LABEL: Record<StageId, string> = {
- reach: "reaching the repository",
- read: "reading its history",
- mine: "mining rules",
- file: "filing the rules",
-};
-
-/** The first rules there are, from whichever count the row has. */
-export function rulesSoFar(repo: RepoState | null): number {
- return Math.max(num(repo?.ruleCount), num(repo?.filedSoFar), num(repo?.foundSoFar));
-}
-
-/**
- * One printable line per stage that has finished since it was last printed.
- *
- * Only for a log with no terminal to redraw — on a TTY the spinner says which
- * stage is running and these lines are never printed. Filing is left out: the
- * watcher hands the prompt back on the first rules, before filing finishes, and
- * the closing line says how many there are.
- */
-export function linesFor(view: BuildView, already: Set<string>, repo: RepoState | null = null): string[] {
- const out: string[] = [];
- for (const s of view.stages) {
- if (s.state !== "done" || s.id === "file") continue;
- const key = `${s.id}:${s.state}`;
- if (already.has(key)) continue;
- already.add(key);
- const rules = rulesSoFar(repo);
- const label =
- s.id === "mine" && rules > 0
- ? `mined the first ${rules.toLocaleString("en-US")} rule${rules === 1 ? "" : "s"}`
- : DONE_LABEL[s.id];
- out.push(` ✓ ${label}`);
- }
- return out;
-}
-
-/** The stage the build is in now, for the spinner. */
-export function currentStage(view: BuildView): StageId {
- return (view.stages.find((s) => s.state === "doing" || s.state === "failed") ?? view.stages[view.stages.length - 1]!).id;
-}
-
-/** The failure line: where it stopped, and that nothing was lost. The server's
- * own words follow on the next line, in full. */
-export function failureLines(view: BuildView): string[] {
- const at = view.stages.find((s) => s.state === "failed")?.id ?? "mine";
- const lines = [`✗ the build stopped while ${DOING_LABEL[at]} · nothing was lost — run graft trail push again`];
- if (view.error) lines.push(` ${view.error}`);
- return lines;
-}
-
-export interface WatchOptions {
- /** How long to hold before giving up on a build that is still running. */
- timeoutMs?: number;
- pollMs?: number;
- fetchImpl?: typeof fetch;
- /** Where the lines go. Injected so the tests do not need a console. */
- write?: (line: string) => void;
- sleep?: (ms: number) => Promise<void>;
- /** Print a line per finished stage. Off on a TTY, where a spinner says it. */
- stageLines?: boolean;
- /** Every state read, with its view — the spinner's feed. */
- onState?: (view: BuildView, repo: RepoState) => void;
- /** Follow `GET /events` instead of polling (the server advertised `events`). */
- events?: boolean;
- /** Silence on the stream for this long counts as a drop. Keep-alives come every 15 s. */
- idleMs?: number;
- /** Stream reconnects before falling back to polling. */
- maxReconnects?: number;
-}
-
-/**
- * How the watch ended.
- *
- * `building` is the ordinary success: rules are in the brain and the rest of the
- * history is still being read behind the prompt. `completed` is the same thing
- * after the whole job has finished, which only happens for a repository small
- * enough to be mined in one slice.
- */
-export type WatchOutcome = "completed" | "building" | "failed" | "timed_out" | "unreachable";
-
-/**
- * Hold until the brain has rules, reporting each stage as it settles.
- *
- * Returns on the first rules rather than on the finished job: mining is what
- * fails and it is done by then, and filing the rest is minutes of work nobody
- * needs to watch. The caller prints where to see the rest.
- *
- * Live when the server streams events: each change arrives as it happens
- * instead of up to four seconds late. A stream that drops is reopened up to
- * three times, and after that the watcher polls as it always did — so the
- * worst a broken stream costs is the old behaviour.
- *
- * Fifteen minutes by default. That is far more than the mining now takes, and it
- * stays generous on purpose: a watcher that gives up before the build does would
- * report a healthy build as a timeout, which is the exact confusion this is
- * meant to remove. Giving up says so and says the work continues, because it
- * does.
- */
-export async function watchBuild(link: BrainLink, opts: WatchOptions = {}): Promise<WatchOutcome> {
- const timeoutMs = opts.timeoutMs ?? 15 * 60 * 1000;
- const pollMs = opts.pollMs ?? 4000;
- const write = opts.write ?? ((l: string) => console.error(l));
- // Not unref'd: between polls this timer is the only thing the process is
- // waiting on, and an unref'd one let it exit mid-watch with nothing printed.
- const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
- const fetchImpl = opts.fetchImpl ?? fetch;
- const stageLines = opts.stageLines !== false;
-
- const printed = new Set<string>();
- const startedAt = Date.now();
- const deadline = startedAt + timeoutMs;
- // A row we could never read at all, as opposed to one that answered once and
- // then stopped answering: the first is a broken link or a host that is down
- // and is worth saying, the second is a blip the next poll usually covers.
- let everRead = false;
-
- /** One state read → the outcome it settles, or null to keep watching. */
- const settle = (repo: RepoState | null): WatchOutcome | null => {
- if (!repo) return null;
- everRead = true;
- const view = stagesFrom(repo);
- opts.onState?.(view, repo);
- if (stageLines) for (const line of linesFor(view, printed, repo)) write(line);
- if (view.error) {
- for (const line of failureLines(view)) write(line);
- return "failed";
- }
- if (view.done) return "completed";
- // The ordinary ending now. The job is still filing the rules the miner
- // has handed over, and still mining the older slices of the history, and
- // neither is worth a terminal sitting on it.
- if (view.ready) return "building";
- return null;
- };
-
- if (opts.events) {
- let drops = 0;
- const maxReconnects = opts.maxReconnects ?? 3;
- while (drops <= maxReconnects && Date.now() < deadline) {
- const r = await streamOnce(link, fetchImpl, settle, deadline, opts.idleMs ?? 45_000);
- if (r.outcome) return r.outcome;
- if (r.end === "unsupported" || r.end === "deadline") break;
- if (r.end === "done") {
- // The build ended without the event saying how: read the row once.
- const final = settle(await fetchRepoState(link, fetchImpl));
- if (final) return final;
- break;
- }
- drops++;
- if (drops <= maxReconnects) await sleep(Math.min(1000 * drops, 4000));
- }
- }
-
- for (;;) {
- const outcome = settle(await fetchRepoState(link, fetchImpl));
- if (outcome) return outcome;
- if (Date.now() >= deadline) return everRead ? "timed_out" : "unreachable";
- await sleep(pollMs);
- }
-}
-
-/** One server-sent event. */
-export interface SseEvent {
- event: string;
- data: string;
-}
-
-/**
- * An incremental text/event-stream parser: feed it chunks as they arrive,
- * get back the events they completed. Comments (`: ping`) are dropped; a
- * missing `event:` field means `message`, per the spec.
- */
-export class SseParser {
- private buf = "";
- private event = "";
- private data: string[] = [];
-
- push(chunk: string): SseEvent[] {
- this.buf += chunk;
- const out: SseEvent[] = [];
- for (;;) {
- const nl = this.buf.search(/\r\n|\r|\n/);
- if (nl < 0) break;
- const sep = this.buf.startsWith("\r\n", nl) ? 2 : 1;
- // A lone \r at the very end may be the first half of \r\n: wait for more.
- if (this.buf[nl] === "\r" && sep === 1 && nl === this.buf.length - 1) break;
- const line = this.buf.slice(0, nl);
- this.buf = this.buf.slice(nl + sep);
- if (line === "") {
- if (this.data.length > 0) out.push({ event: this.event || "message", data: this.data.join("\n") });
- this.event = "";
- this.data = [];
- continue;
- }
- if (line.startsWith(":")) continue;
- const colon = line.indexOf(":");
- const field = colon < 0 ? line : line.slice(0, colon);
- let value = colon < 0 ? "" : line.slice(colon + 1);
- if (value.startsWith(" ")) value = value.slice(1);
- if (field === "event") this.event = value;
- else if (field === "data") this.data.push(value);
- // id and retry are not used: a reconnect starts from a fresh `progress`.
- }
- return out;
- }
-}
-
-type StreamEnd = "done" | "dropped" | "unsupported" | "deadline";
-
-/**
- * One connection to `GET /events`. Resolves with the outcome when an event
- * settled the watch, or with how the stream ended when none did.
- */
-async function streamOnce(
- link: BrainLink,
- fetchImpl: typeof fetch,
- settle: (repo: RepoState | null) => WatchOutcome | null,
- deadline: number,
- idleMs: number,
-): Promise<{ outcome?: WatchOutcome; end?: StreamEnd }> {
- const ctl = new AbortController();
- let res: Response;
- try {
- res = await fetchImpl(`${baseUrlFor(link)}/api/public/brains/${encodeURIComponent(link.brainId)}/events`, {
- headers: { authorization: `Bearer ${link.token}`, accept: "text/event-stream", "cache-control": "no-cache" },
- signal: ctl.signal,
- });
- } catch {
- return { end: "dropped" };
- }
- // A server without the route, or one that answered with something other
- // than a stream: polling is the answer, not three more tries.
- if (res.status === 404 || res.status === 405 || res.status === 501) return { end: "unsupported" };
- if (!res.ok) return { end: "dropped" };
- const type = res.headers?.get?.("content-type") ?? "text/event-stream";
- if (!res.body || !/event-stream/i.test(type)) return { end: "unsupported" };
-
- const reader = res.body.getReader();
- const decoder = new TextDecoder();
- const parser = new SseParser();
- try {
- for (;;) {
- const left = deadline - Date.now();
- if (left <= 0) return { end: "deadline" };
- let timer: NodeJS.Timeout | undefined;
- const idle = new Promise<"idle">((r) => {
- // Not unref'd: while the stream is quiet this timer is what the
- // process is waiting on, and it is cleared the moment a chunk lands.
- timer = setTimeout(() => r("idle"), Math.min(idleMs, left));
- });
- const got = await Promise.race([reader.read(), idle]).finally(() => clearTimeout(timer));
- if (got === "idle") return { end: Date.now() >= deadline ? "deadline" : "dropped" };
- if (got.done) return { end: "dropped" };
- for (const ev of parser.push(decoder.decode(got.value, { stream: true }))) {
- let payload: unknown = null;
- try {
- payload = ev.data ? JSON.parse(ev.data) : null;
- } catch {
- payload = null;
- }
- if (ev.event === "progress" || ev.event === "message") {
- const outcome = settle(parseRepoBody(payload));
- if (outcome) return { outcome };
- } else if (ev.event === "done") {
- const outcome = settle(parseRepoBody(payload));
- if (outcome) return { outcome };
- return { end: "done" };
- }
- }
- }
- } catch {
- return { end: "dropped" };
- } finally {
- ctl.abort();
- try {
- reader.releaseLock();
- } catch {
- /* already released by the abort */
- }
- }
-}
diff --git a/src/brain/wire.ts b/src/brain/wire.ts
deleted file mode 100644
index 4a10fc5d..00000000
--- a/src/brain/wire.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-/**
- * Writing a brain's rules into the instruction file each coding agent already
- * reads.
- *
- * Two delivery paths exist and both matter. Every `graft ask` carries the rules
- * for the symbols in its answer — that is the precise one. This is the broad
- * one: the repo-wide conventions, sitting in `AGENTS.md` / `CLAUDE.md` /
- * `.cursor/rules` where the agent picks them up whether or not it ever calls
- * graft.
- *
- * The rules land in their OWN fenced block (`BRAIN_MARKERS`), never inside the
- * instruction block: instructions are static and rewritten by `init`, rules
- * change whenever the brain does, and `uninstall` has to be able to remove
- * either one.
- */
-import { join } from 'node:path';
-import { HOSTS, detectHosts, type DetectProbe, type HostTarget } from '../hosts/registry.js';
-import { upsertSection, BRAIN_MARKERS, type UpsertAction } from '../hosts/sections.js';
-import { statSync } from 'node:fs';
-import type { BrainRule } from './link.js';
-
-/** How many rules go into an instruction file. */
-const MAX_FILE_RULES = 40;
-
-/** What a rules write did to one host's file. */
-export interface BrainWrite {
- id: string;
- path: string;
- action: UpsertAction;
-}
-
-/**
- * Render the rules block for an instruction file.
- *
- * Grouped by the file the rule governs, because that is how someone reads a
- * codebase, and repo-wide rules (no symbol) come first — they apply everywhere,
- * so they should not be buried under a path heading.
- */
-export function renderBrainSection(rules: BrainRule[], repoLabel: string): string {
- const capped = rules.slice(0, MAX_FILE_RULES);
- const lines = [
- '## House rules for this codebase',
- '',
- `Mined from ${repoLabel}'s own history — commit messages and pull-request`,
- 'discussion — by Trail. These are decisions the team has already made, so',
- 'follow them and do not re-litigate them in passing. Each is attributed to',
- 'what established it.',
- '',
- ];
-
- const byFile = new Map<string, BrainRule[]>();
- for (const r of capped) {
- // A node id is `<path>#<QualifiedName>`; everything before the '#' is the file.
- const file = r.symbol.includes('#') ? r.symbol.slice(0, r.symbol.indexOf('#')) : '';
- const bucket = byFile.get(file);
- if (bucket) bucket.push(r);
- else byFile.set(file, [r]);
- }
-
- const general = byFile.get('') ?? [];
- for (const r of general) lines.push(`- ${r.rule}${r.sourceUrl ? ` (${r.sourceUrl})` : ''}`);
- if (general.length) lines.push('');
-
- for (const [file, group] of [...byFile].filter(([f]) => f !== '').sort()) {
- lines.push(`### ${file}`);
- for (const r of group) lines.push(`- ${r.rule}${r.sourceUrl ? ` (${r.sourceUrl})` : ''}`);
- lines.push('');
- }
-
- if (rules.length > capped.length) {
- lines.push(
- `_${rules.length - capped.length} more rules apply to specific symbols; graft attaches those to each \`graft ask\` answer._`,
- );
- }
- return lines.join('\n').trimEnd();
-}
-
-/** Build the probe `detectHosts` needs. Mirrors hosts/init.ts's own. */
-function probeFor(repo: string, home: string): DetectProbe {
- return {
- home,
- repo,
- dirExists: (p: string) => {
- try {
- return statSync(p).isDirectory();
- } catch {
- return false;
- }
- },
- };
-}
-
-/**
- * Every instruction file a brain section should go in.
- *
- * `section`-kind hosts only. An `owned`-kind host (Cursor's `.mdc`, Kiro's
- * steering file, a `SKILL.md`) is a file graft rewrites whole from a pure
- * template, so a second managed region inside one would be erased by the next
- * `init` — those agents get their rules through `graft ask` instead, which they
- * all call.
- *
- * Deduplicated by path: three hosts target `AGENTS.md`, and writing it three
- * times in one pass is just three identical upserts.
- */
-export function brainSectionTargets(repo: string, home: string, ids?: string[]): HostTarget[] {
- const selected = ids?.length
- ? HOSTS.filter((h) => ids.includes(h.id))
- : detectHosts(probeFor(repo, home));
- const seen = new Set<string>();
- const out: HostTarget[] = [];
- for (const h of selected) {
- if (h.kind !== 'section') continue;
- if (seen.has(h.relPath)) continue;
- seen.add(h.relPath);
- out.push(h);
- }
- return out;
-}
-
-/**
- * Write the brain's rules into each selected host's instruction file.
- *
- * Best-effort per file: one unwritable path must not stop the rest, since a
- * partially delivered rulebook is strictly better than none.
- */
-export function writeBrainSections(
- repo: string,
- home: string,
- rules: BrainRule[],
- repoLabel: string,
- ids?: string[],
-): BrainWrite[] {
- if (!rules.length) return [];
- const body = renderBrainSection(rules, repoLabel);
- const out: BrainWrite[] = [];
- for (const host of brainSectionTargets(repo, home, ids)) {
- const path = join(repo, host.relPath);
- try {
- const { action } = upsertSection(path, body, BRAIN_MARKERS);
- out.push({ id: host.id, path, action });
- } catch {
- // Unwritable file (read-only checkout, a directory in the way). Skipped
- // silently here; the caller reports what it did get.
- }
- }
- return out;
-}
diff --git a/src/brand.ts b/src/brand.ts
index 72d2fd5f..ef583fc8 100644
--- a/src/brand.ts
+++ b/src/brand.ts
@@ -46,15 +46,10 @@ export function tag(env: NodeJS.ProcessEnv = process.env): string {
/**
* The commands whose trail spelling is not just `graft` → `trail`, longest
- * prefix first. `graft check` gave its name to the team check, `graft stats`
- * and `graft trail status` became one `trail status`, and the `graft trail …`
- * group moved to the top level.
+ * prefix first. `graft check` gave its name to the team check, and `graft
+ * stats` became `trail status`.
*/
const RENAMED: ReadonlyArray<readonly [string, string]> = [
- ["graft trail disconnect", "trail logout"],
- ["graft trail connect", "trail login"],
- ["graft trail status", "trail status"],
- ["graft trail", "trail"],
["graft check", "trail build --check"],
["graft stats", "trail status"],
["graft", "trail"],
@@ -63,8 +58,7 @@ const RENAMED: ReadonlyArray<readonly [string, string]> = [
/**
* A command as the running name spells it. Takes the graft spelling, so call
* sites read the way they always have and graft's output does not change:
- * `cmd("graft trail push")` is `graft trail push` under graft and `trail push`
- * under trail.
+ * `cmd("graft ask")` is `graft ask` under graft and `trail ask` under trail.
*/
export function cmd(graftSpelling: string, b: Brand = brand()): string {
if (b === "graft") return graftSpelling;
@@ -151,7 +145,7 @@ export function commandOnPath(name: string, env: NodeJS.ProcessEnv = process.env
}
export interface NoticeInput {
- /** The graft spelling of what just ran, e.g. `graft ask` or `graft trail status`. */
+ /** The graft spelling of what just ran, e.g. `graft ask` or `graft build`. */
ran: string;
/** stderr is a terminal: a person is watching. */
tty: boolean;
diff --git a/src/claude/hooks.ts b/src/claude/hooks.ts
index bd5b3d45..214d7022 100644
--- a/src/claude/hooks.ts
+++ b/src/claude/hooks.ts
@@ -15,10 +15,6 @@ import { flushClosedSessions, summarizeSession } from '../telemetry/sessions.js'
import { hasSavingsTally, lastAssistantTurn, lastTurnBilling } from './tally.js';
import { scopeOf, scopesOfGraph } from '../graph/scopes.js';
import { classifyToolUse, isMcpToolName, isGraftMcpTool, parseSavings, recordToolUse, type ToolKind } from './session-metrics.js';
-import { readLink } from '../brain/link.js';
-import { pickedAgents } from '../brain/push.js';
-import { readTrailSnapshot, trailContextLine } from '../brain/watch-trail.js';
-import { maybeAutopush, readTrailPushState, recordSeenSuggestions, type AutopushDeps } from '../brain/autopush.js';
import { adoptRepoBrand, brand, cmd, commandOnPath, repoWiredForTrail, tag, trailOnPath } from '../brand.js';
import { fitTrailServerToMachine } from '../hosts/claude-global.js';
import { NOTE_CALL } from '../notes/session-cost.js';
@@ -467,69 +463,6 @@ function handleStop(input: any, dir: string): void {
}
}
-/** The most the session-start hook waits on Trail. */
-export const TRAIL_CHECK_CAP_MS = 3000;
-
-/**
- * What the attached trail has waiting, as one line for the session's opening
- * context — and, on the way, the once-a-day background push that keeps it
- * current (brain/autopush.ts). Null when there is no trail, nothing waiting, or
- * no answer in time.
- *
- * The one place a hook goes to the network, and it is fenced accordingly. Only a
- * repo with a trail attached asks at all, so every other repo pays nothing. The
- * requests are aborted at {@link TRAIL_CHECK_CAP_MS} — or sooner when the
- * installed hook budget is tighter — and raced against a timer besides, so a
- * Trail that never answers costs the session three seconds, once, and never the
- * hook: the orientation below is emitted either way, and the hook is not
- * killed. Anything that goes wrong is a missing line, never a thrown error.
- *
- * Worth the three seconds because nothing else tells anyone. Changes accepted in
- * Trail sit there until someone remembers `graft trail pull`, and suggestions
- * nobody has looked at sit there longer; the start of a session is when an
- * agent can ask the person about them. Suggestions are mentioned only when
- * there are new ones since the last session (see trailContextLine), so the
- * line never becomes a fixture of every session.
- */
-export async function trailAtSessionStart(
- dir: string,
- deps: { fetchImpl?: typeof fetch; capMs?: number; autopush?: AutopushDeps } = {},
-): Promise<string | null> {
- let timer: NodeJS.Timeout | undefined;
- try {
- const link = readLink(dir);
- if (!link) return null;
- const installed = installedHookTimeout(dir, 'SessionStart');
- const cap = deps.capMs ?? Math.min(TRAIL_CHECK_CAP_MS, Math.max(1000, (installed ?? CHILD_TIMEOUT_MS) - HOOK_OVERHEAD_MS));
- const ctl = new AbortController();
- const f = deps.fetchImpl ?? fetch;
- // Our signal replaces the per-request ones (5 and 15 s), which are all
- // longer than the cap and would otherwise keep the process alive past it.
- const capped = ((input: Parameters<typeof fetch>[0], init?: RequestInit) => f(input, { ...init, signal: ctl.signal })) as typeof fetch;
- const snapshot = readTrailSnapshot(dir, link, pickedAgents(dir), capped);
- // Started while the requests are in flight; it only spawns and returns.
- maybeAutopush(dir, deps.autopush);
- const late = new Promise<null>((r) => {
- timer = setTimeout(() => {
- ctl.abort();
- r(null);
- }, cap);
- });
- const r = await Promise.race([snapshot, late]);
- if (!r || !r.ok) return null;
- // Read before the new count is written: the line says what grew since the
- // last session, and every successful check moves that mark — including one
- // whose line was about accepted changes instead.
- const lastSeen = readTrailPushState(dir).seenSuggested;
- if (r.snapshot.suggested !== null) recordSeenSuggestions(dir, r.snapshot.suggested);
- return trailContextLine(r.snapshot, lastSeen);
- } catch {
- return null;
- } finally {
- clearTimeout(timer);
- }
-}
-
const DAY_MS = 24 * 60 * 60 * 1000;
/**
@@ -644,10 +577,6 @@ export async function main(event: string): Promise<void> {
adoptRepoBrand(dir);
if (event === 'session-start') {
- // The trail's quick look goes first, so its requests are in flight while the
- // rest of this runs. It is the hook's one network call, capped and only for
- // a repo with a trail — see trailAtSessionStart.
- const trail = trailAtSessionStart(dir);
// Before anything is emitted: refresh this repo's wiring if it was written by
// an older graft, and pick up any cached "newer version on npm" answer.
// background:false — the registry check stays off the network here; the CLI
@@ -659,8 +588,6 @@ export async function main(event: string): Promise<void> {
trailAtStart(dir);
// A repo on trail, opened on a machine that has graft but not the trail command.
if (repoWiredForTrail(dir)) fitTrailServerToMachine(homedir(), resolve(dir), { trail: trailOnPath(), graft: commandOnPath('graft') });
- const trailLine = await trail;
- if (trailLine) upkeep.push(trailLine);
try {
const idx = readFileSync(join(resolveContextDir(dir), 'INDEX.md'), 'utf8');
const banner = staleBanner(indexFreshness(dir)) ?? undefined;
diff --git a/src/cli.ts b/src/cli.ts
index aef22f5c..b0990f9d 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -24,49 +24,9 @@ import { statuslineWanted } from "./claude/settings-merge.js";
import { runHostsInit } from "./hosts/init.js";
import { hostIds } from "./hosts/registry.js";
import { checkoutRoot, ensureRepoHome, keepsNotes, noteCount, rememberRepo, repoName, repoPlace, shownPath } from "./notes/home.js";
-import { parseBrainArg, connectBrain, pullBrain, brainStatus } from "./brain/connect.js";
-import { rulesForPointers } from "./brain/attach.js";
-import { clearLink, type BrainLink } from "./brain/link.js";
-import {
- buildEarlyDigest,
- buildLocalDigest,
- fetchExpectedRepo,
- pickedAgents,
- pushContext,
- pushDigest,
- pushEarlyDigest,
- repoSlugFromGit,
- sameRepo,
- uploadCaps,
-} from "./brain/push.js";
-import { apiBaseUrl, clearPendingSignup, readLink, readPendingSignup, writeLink, writePendingSignup } from "./brain/link.js";
-import { withLegacyNames } from "./legacy-args.js";
import { brand, cmd, graftNotice, tag } from "./brand.js";
import { branchDiff } from "./cloud/diff.js";
-import { currentStage, DOING_LABEL, rulesSoFar, watchBuild, type RepoState } from "./brain/watch.js";
-import {
- AGENT_WAIT_MS,
- brainUrl,
- newSignupState,
- openBrowser,
- PENDING_SIGNUP_TTL_MS,
- reviewUrl,
- signupUrl,
- startHandoff,
- waitForSignup,
-} from "./brain/signup.js";
-import { runTrailPull, suggestionsLine } from "./brain/pull.js";
-import {
- trackWatchExit,
- WATCH_DEFAULTS,
- watchExitCode,
- watchExitJson,
- watchExitLines,
- watchTrail,
- type WatchTrailResult,
-} from "./brain/watch-trail.js";
-import { AUTOPUSH_CHILD_ENV, recordTrailPush } from "./brain/autopush.js";
-import { startSpinner } from "./util/spinner.js";
+import { openBrowser } from "./util/browser.js";
import { contextDirFor } from "./context/node-file.js";
import { loadGraphCached } from "./graph/load.js";
import { ensureFreshChildren, ensureFreshGraph, refreshNote } from "./graph/refresh.js";
@@ -300,7 +260,7 @@ function parseTabs(raw: string | undefined): VizTab[] | undefined {
* not editorialize on stderr at startup (`mcp` runs its own upkeep at boot, and
* `_update-check` IS the fetch).
*/
-const UPKEEP_SKIP = new Set(["version", "upgrade", "_update-check", "_brain-refresh", "_trail-past-read", "mcp"]);
+const UPKEEP_SKIP = new Set(["version", "upgrade", "_update-check", "_trail-past-read", "mcp"]);
/**
* Every other command: top up the cached registry answer in the background and,
@@ -338,29 +298,13 @@ program.hook("postAction", (_parent, action) => {
track("query", { command: name, surface: "cli", hit: queryNote.hit, notes: queryNote.notes }, { repo: queryNote.repo });
});
-/** `graft ask`, `graft trail status`: a command as graft spells it, whatever ran it. */
+/** `graft ask`, `graft build`: a command as graft spells it, whatever ran it. */
function spelling(action: Command): string {
const words: string[] = [];
for (let c: Command | null = action; c && c.parent; c = c.parent) words.unshift(c.name());
return ["graft", ...words].join(" ");
}
-// Hidden from --help: only ever spawned detached by maybeRefreshInBackground.
-program
- .command("_brain-refresh", { hidden: true })
- .description("internal: re-pull the attached brain's rules and rewrite the agent files")
- .argument("[dir]", "target repo directory", ".")
- .action(async (dir: string) => {
- // Spawned detached by upkeep, so nothing here is user-visible and nothing
- // may throw: a failure means the cached rules keep serving, which is the
- // correct outcome for a brain that is momentarily unreachable.
- try {
- await pullBrain(resolve(dir), { home: homedir() });
- } catch {
- /* the next session tries again */
- }
- });
-
// Hidden: spawned detached by maybeSyncInBackground when a workspace repo's
// learnings changed, or uses are waiting to go. Running it by hand syncs now.
// A repo that moved from graft to trail at session start reads its past
@@ -1341,7 +1285,6 @@ grouped(program.command("init"), GROUP.setup)
.option("--dry-run", "print every file init would touch, then exit without writing")
.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("--trail <handoff>", "attach a Trail: <brainId>:<token> (or a bare id with GRAFT_BRAIN_TOKEN set)")
.option("--verbose", "print every file written, the graph build's own output and the closing banner")
.action(async (dir: string, opts: InitOptions) => {
await runInitCommand(dir, opts);
@@ -1465,46 +1408,19 @@ 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; trail?: string; verbose?: boolean }
-
-/** `a, b and c`. */
-function joinAnd(items: string[]): string {
- if (items.length <= 1) return items.join("");
- return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
-}
+interface InitOptions { build?: boolean; agents?: string[]; allAgents?: boolean; listAgents?: boolean; mcp?: boolean; hooks?: boolean; statusline?: boolean; dryRun?: boolean; yes?: boolean; global?: boolean; verbose?: boolean }
/** Repo-relative with forward slashes, for printing. */
function shown(repo: string, path: string): string {
return relative(repo, path).split("\\").join("/");
}
-/**
- * `graft init`. Also run by `graft trail push` on a repo graft has not been set
- * up in — the Trail pages start people at push, and a trail whose rules no
- * coding agent reads is only half set up. `epilogue: false` leaves out the
- * closing banner when push is going to keep talking.
- */
-async function runInitCommand(
- dir: string,
- opts: InitOptions,
- how: { epilogue?: boolean; push?: boolean } = {},
-): Promise<{ ids: string[] } | null> {
+/** `graft init`. */
+async function runInitCommand(dir: string, opts: InitOptions): Promise<{ ids: string[] } | null> {
if (opts.listAgents) {
for (const id of [...hostIds(), "claude"]) console.log(id);
return null;
}
- // Parsed before anything is written: a mistyped handoff should cost the user
- // an error, not a half-wired repo they have to `graft uninstall` out of.
- let brainLink: BrainLink | undefined;
- if (opts.trail) {
- const parsed = parseBrainArg(opts.trail);
- if ("error" in parsed) {
- console.error(`✗ --trail: ${parsed.error}`);
- process.exitCode = 1;
- return null;
- }
- brainLink = parsed;
- }
const repo = resolve(dir);
const explicit = Array.isArray(opts.agents) ? opts.agents : undefined;
@@ -1540,8 +1456,6 @@ async function runInitCommand(
const reason = offReason();
const picked = await runPicker(plan, repo, home, {
offerTelemetry: reason === null || reason === "disabled",
- // From push, the line above the picker already asks the question.
- ...(how.push ? { title: null } : {}),
});
if (picked === null) {
console.error("· cancelled — nothing written");
@@ -1616,21 +1530,18 @@ async function runInitCommand(
// The graph, built once after the wiring: a workspace parent's build is
// the workspace build, so it covers every child.
let graphLine: string | null = null;
- let graphNodes = 0;
if (!verbose) {
const res = await buildGraphWithProgress(repo, { build: opts.build, cliPath });
for (const m of res.messages) console.error(m);
const existing = res.built ? null : loadGraphCached(contextDirFor(repo, children.length ? undefined : program.opts<GlobalOpts>().dir));
const fmt = (x: number) => x.toLocaleString("en-US");
if (res.graph) {
- graphNodes = res.graph.nodes;
graphLine = `✓ graph built · ${fmt(res.graph.nodes)} nodes, ${fmt(res.graph.edges)} edges${res.graph.files ? ` from ${fmt(res.graph.files)} file${res.graph.files === 1 ? "" : "s"}` : ""}`;
} else if (res.built) {
graphLine = "✓ graph built";
} else if (res.failed) {
graphLine = `⚠ the graph build failed — run ${cmd("graft build")} to see why`;
} else if (existing) {
- graphNodes = existing.meta.nodeCount;
graphLine = `✓ graph ready · ${fmt(existing.meta.nodeCount)} nodes, ${fmt(existing.meta.edgeCount)} edges`;
} else if (hasGraftIndex(repo)) {
graphLine = "✓ graph ready";
@@ -1646,17 +1557,11 @@ async function runInitCommand(
for (const w of reports.flatMap((r) => r.warnings)) console.error(w);
const writesFor = (id: string) =>
(plan.find((p) => p.id === id)?.writes ?? []).filter((w) => opts.global !== false || w.scope !== "global");
- if (how.push) {
- const built = graphLine?.startsWith("✓ graph built") ? `graph built, ${graphNodes.toLocaleString("en-US")} nodes` : graphLine?.startsWith("✓") ? "graph ready" : null;
- console.error(`✓ wired ${joinAnd(ids)}${built ? ` · ${built}` : ""}`);
- if (graphLine && !graphLine.startsWith("✓")) console.error(graphLine);
- } else {
- if (graphLine) console.error(graphLine);
- const width = Math.max(...ids.map((id) => id.length));
- for (const id of ids) {
- const summary = compactWrites(writesFor(id), repo, home);
- console.error(`✓ ${id.padEnd(width)} ${summary}`.trimEnd());
- }
+ if (graphLine) console.error(graphLine);
+ const width = Math.max(...ids.map((id) => id.length));
+ for (const id of ids) {
+ const summary = compactWrites(writesFor(id), repo, home);
+ console.error(`✓ ${id.padEnd(width)} ${summary}`.trimEnd());
}
}
@@ -1686,29 +1591,7 @@ async function runInitCommand(
}
}
- // The brain comes last, after the graph exists: its rules are anchored to
- // symbols, and `graft trail status` can only report how many of them resolve
- // once there is a graph to resolve them against.
- if (brainLink) {
- const res = await connectBrain(repo, brainLink, { home, ids });
- if (verbose) {
- if (res.warning) console.error(`⚠ brain: ${res.warning}`);
- else console.error(`✓ brain: pulled ${res.ruleCount} rule(s) from ${brainLink.brainId}`);
- for (const w of res.writes) console.error(`✓ brain rules: ${w.path} (${w.action})`);
- if (res.ruleCount > 0 && res.writes.length === 0)
- console.error(`· no instruction file to write rules into — ${cmd("graft ask")} still carries them`);
- } else if (res.warning) {
- console.error(`⚠ trail: ${res.warning}`);
- } else if (res.ruleCount === 0) {
- console.error(`✓ trail connected · no rules yet — ${cmd("graft trail push")} reads this repo into it`);
- } else {
- const where = res.writes.map((w) => shown(repo, w.path)).join(", ");
- const n = `${res.ruleCount.toLocaleString("en-US")} rule${res.ruleCount === 1 ? "" : "s"}`;
- console.error(`✓ trail connected · ${n}${where ? ` in ${where}` : ""}`);
- }
- }
-
- if (!verbose && how.epilogue !== false) {
+ if (!verbose) {
// What there is to commit: the top-level entries the picked agents wrote.
const tops: string[] = [];
for (const w of selectedWrites(plan, ids)) {
@@ -1738,7 +1621,7 @@ async function runInitCommand(
const graphs = (children.length ? children.map((c) => join(repo, c)) : [repo])
.map((d) => loadGraphCached(contextDirFor(d, children.length ? undefined : globalDir)))
.filter((g): g is NonNullable<typeof g> => g !== null);
- if (verbose && how.epilogue !== false) console.error(
+ if (verbose) console.error(
"\n" +
formatInitEpilogue({
graphBuilt: graphs.length > 0,
@@ -1927,544 +1810,6 @@ grouped(program.command("uninstall"), GROUP.setup)
});
-/**
- * Get this repo a trail 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. Nothing about the repository has been read or sent
- * by then, and every message says so.
- */
-async function signUpForBrain(repo: string, slug: string): Promise<BrainLink | null> {
- // No terminal means an agent is running this, and a loopback listener cannot
- // outlive the command it is waiting in: see signUpWithoutTerminal.
- if (!process.stderr.isTTY) return signUpWithoutTerminal(repo, slug);
- const handoff = await startHandoff();
- const url = signupUrl({ repo: slug, port: handoff.port, state: handoff.state });
- const startedAt = Date.now();
-
- // Queued before the link is printed rather than after the outcome, because
- // the outcome is the one thing a terminal handoff can lose: a user who reads
- // the URL and walks away kills the process, and only an event already on disk
- // survives that. This is the denominator; `brain_signup_settled` is not.
- track("brain_signup_opened", { mode: "terminal" }, { repo });
-
- // 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 trail yet — opening your browser to make one:`);
- console.error(` ${url}`);
-
- openBrowser(url);
- const spinner = startSpinner("waiting for you to finish signing up · Ctrl-C to stop");
-
- // Ctrl-C while waiting is a person changing their mind, not a crash: say that
- // nothing was sent, and leave with the usual interrupted exit code.
- let onSigint: (() => void) | undefined;
- const stopped = new Promise<"stopped">((resolve) => {
- onSigint = () => resolve("stopped");
- process.once("SIGINT", onSigint);
- });
- const got = await Promise.race([handoff.wait(), stopped]);
- if (onSigint) process.off("SIGINT", onSigint);
- spinner.stop();
- if (got === "stopped") {
- handoff.close();
- console.error(`· stopped — nothing was sent; run ${cmd("graft trail push")} again when you're ready`);
- track("brain_signup_settled", { outcome: "stopped", mode: "terminal", duration_bucket: durationBucket(Date.now() - startedAt) }, { repo });
- process.exitCode = 130;
- return null;
- }
- if ("error" in got) {
- console.error(`✗ ${got.error}`);
- // The category, never the sentence: `got.error` names the repo and the link.
- track("brain_signup_settled", { outcome: got.reason, mode: "terminal", duration_bucket: durationBucket(Date.now() - startedAt) }, { repo });
- return null;
- }
- writeLink(repo, got.link);
- console.error(`✓ trail connected · ${slug} — your browser shows it building`);
- track("brain_signup_settled", { outcome: "linked", mode: "terminal", duration_bucket: durationBucket(Date.now() - startedAt) }, { repo });
- return got.link;
-}
-
-/**
- * The same sign-up when an agent runs the push, in two runs of one command.
- *
- * An agent shows the person nothing until a command exits, so the first run
- * opens the sign-up page, saves the state in its link and exits at once, with
- * a line telling the agent what to do next. The run after that finds the saved
- * state and asks Trail for the trail it made, for up to AGENT_WAIT_MS, then
- * carries on with the push. Still not signed up by then, it says so and the
- * agent runs it again. Nothing about the repository is read or sent until the
- * trail is linked.
- */
-async function signUpWithoutTerminal(repo: string, slug: string): Promise<BrainLink | null> {
- const startedAt = Date.now();
- const settled = (outcome: string) =>
- track("brain_signup_settled", { outcome, mode: "agent", duration_bucket: durationBucket(Date.now() - startedAt) }, { repo });
- const pending = readPendingSignup(repo, slug, PENDING_SIGNUP_TTL_MS);
-
- if (!pending) {
- const state = newSignupState();
- writePendingSignup(repo, { state, repo: slug, createdAt: Date.now() });
- const url = signupUrl({ repo: slug, state });
- track("brain_signup_opened", { mode: "agent" }, { repo });
- openBrowser(url);
- console.error(`· ${slug} has no trail yet — opened Trail's sign-up page in the browser:`);
- console.error(` ${url}`);
- console.error("· nothing has been read or sent yet.");
- console.error(
- `· next: ask the user to sign up in the tab that just opened (or at the link above), then run \`${cmd("graft trail push")}\` again straight away — it waits for the sign-up to finish and carries on with the push. Don't wait for them to reply first.`,
- );
- settled("agent_link_opened");
- process.exitCode = 1;
- return null;
- }
-
- const url = signupUrl({ repo: slug, state: pending.state });
- console.error(`· waiting up to ${Math.round(AGENT_WAIT_MS / 1000)} s for the sign-up for ${slug} to finish:`);
- console.error(` ${url}`);
- const got = await waitForSignup(pending.state, apiBaseUrl());
-
- if ("link" in got) {
- clearPendingSignup(repo);
- writeLink(repo, got.link);
- console.error(`✓ trail connected · ${slug}`);
- settled("linked");
- return got.link;
- }
- if ("pending" in got) {
- console.error("· not signed up yet — nothing has been read or sent.");
- console.error(`· next: run \`${cmd("graft trail push")}\` again to keep waiting. The link above stays valid for about 15 minutes.`);
- settled("still_waiting");
- process.exitCode = 1;
- return null;
- }
- clearPendingSignup(repo);
- console.error(`✗ ${got.error}`);
- settled(got.reason);
- process.exitCode = 1;
- return null;
-}
-
-function connectCommand(name = "connect"): Command {
- return new Command(name)
- .description("Attach a brain to this repo and pull its rules")
- .argument("<handoff>", "<brainId>:<token>, or a bare brain id with GRAFT_BRAIN_TOKEN set")
- .argument("[dir]", "target repo directory", ".")
- .action(async (handoff: string, dir: string) => {
- await runConnect(handoff, dir);
- });
-}
-
-/** `graft trail connect`, and `trail login <handoff>`: attach a trail from a Trail page's handoff. */
-async function runConnect(handoff: string, dir: string): Promise<void> {
- const parsed = parseBrainArg(handoff);
- if ("error" in parsed) {
- console.error(`✗ ${parsed.error}`);
- process.exitCode = 1;
- return;
- }
- const repo = resolve(dir);
- const res = await connectBrain(repo, parsed, { home: homedir() });
- if (res.warning) {
- console.error(`⚠ ${res.warning}`);
- return;
- }
- if (res.ruleCount === 0) {
- // The normal case on the local route: the brain exists but nothing has
- // read the repo yet. Saying "0 rules" without saying why reads as a
- // failure, and the next step is the whole point.
- console.error("✓ attached this repo to the brain — it has no rules yet");
- console.error(`· run \`${cmd("graft trail push")}\` to read this repository into it`);
- return;
- }
- console.error(`✓ pulled ${res.ruleCount} rule(s) from ${parsed.brainId}`);
- for (const w of res.writes) console.error(`✓ ${w.path} (${w.action})`);
-}
-
-function pullCommand(name = "pull"): Command {
- return new Command(name)
- .description("Refresh the trail's rules and write every change you accepted in Trail into this repo's context files")
- .argument("[dir]", "target repo directory", ".")
- .option("--dry-run", "show what would change without writing anything or telling Trail")
- .action(async (dir: string, opts: { dryRun?: boolean }) => {
- await runTrailPullCommand(dir, opts);
- });
-}
-
-/** `graft trail pull`, and `graft claude-md pull` which is now the same thing. */
-async function runTrailPullCommand(dir: string, opts: { dryRun?: boolean }): Promise<void> {
- const repo = resolve(dir);
- const link = readLink(repo);
- if (!link) {
- console.error(`✗ this repo has no trail yet — run ${cmd("graft trail push")} first`);
- process.exitCode = 1;
- return;
- }
- const stamp = readStamp(repo);
- const wired = [...new Set([...(stamp?.hosts ?? []), ...wiredHostIds(repo)])];
- const code = await runTrailPull(repo, link, { home: homedir(), wired, dryRun: opts.dryRun });
- if (code !== 0) process.exitCode = code;
-}
-
-/** A positive number of seconds or minutes from an option, or null. */
-function positiveNumber(raw: string): number | null {
- const n = Number(raw);
- return Number.isFinite(n) && n > 0 ? n : null;
-}
-
-function watchCommand(name = "watch"): Command {
- return new Command(name)
- .description("Wait until Trail has suggestions to review or accepted changes to pull, then say so once")
- .argument("[dir]", "target repo directory", ".")
- .option("--interval <seconds>", "how often to check Trail", String(WATCH_DEFAULTS.intervalMs / 1000))
- .option("--settle <seconds>", "how long the accepted changes must stay the same before they are reported", String(WATCH_DEFAULTS.settleMs / 1000))
- .option("--timeout <minutes>", "give up after this long (exit code 2)", String(WATCH_DEFAULTS.timeoutMs / 60_000))
- .option("--accepted-only", "keep waiting while suggestions are only waiting for review; stop on accepted changes")
- .option("--json", "print the result as JSON")
- .option("--verbose", "print the counts on every check, to stderr")
- .addHelpText(
- "after",
- [
- "",
- "Stops when any of these is true, and prints one block to stdout:",
- " - there are suggestions and none accepted (unless --accepted-only) exit 0",
- " - accepted changes have not changed for --settle seconds exit 0",
- " - --timeout minutes have passed exit 2",
- "A failed check is retried on the next one. No trail attached, or a token Trail refuses: exit 1.",
- ].join("\n"),
- )
- .action(
- async (
- dir: string,
- opts: { interval: string; settle: string; timeout: string; acceptedOnly?: boolean; json?: boolean; verbose?: boolean },
- ) => {
- const repo = resolve(dir);
- const interval = positiveNumber(opts.interval);
- const settle = Number(opts.settle);
- const timeout = positiveNumber(opts.timeout);
- if (interval === null || timeout === null || !Number.isFinite(settle) || settle < 0) {
- console.error("✗ --interval and --timeout take a number above zero, --settle a number of seconds (0 or more)");
- process.exitCode = 1;
- return;
- }
- const timeoutMs = timeout * 60_000;
- const finish = (r: WatchTrailResult) => {
- if (opts.json) console.log(JSON.stringify(watchExitJson(r), null, 2));
- else for (const line of watchExitLines(r, timeoutMs)) console.log(line);
- trackWatchExit(repo, r);
- const code = watchExitCode(r);
- if (code !== 0) process.exitCode = code;
- };
- const link = readLink(repo);
- if (!link) {
- finish({ reason: "no_trail", suggested: null, accepted: 0, files: [], reviewUrl: "", waitedMs: 0, everRead: false });
- return;
- }
- const result = await watchTrail(repo, link, {
- wired: pickedAgents(repo),
- intervalMs: interval * 1000,
- settleMs: settle * 1000,
- timeoutMs,
- acceptedOnly: opts.acceptedOnly === true,
- onTick: opts.verbose
- ? (r) => {
- const at = new Date().toTimeString().slice(0, 8);
- if (!r.ok) console.error(`· ${at} ${r.fatal ? "refused" : "retrying next check"}: ${r.error}`);
- else console.error(`· ${at} ${r.snapshot.suggested ?? "?"} suggested, ${r.snapshot.accepted} accepted`);
- }
- : undefined,
- });
- finish(result);
- },
- );
-}
-
-function pushCommand(name = "push"): Command {
- return new Command(name)
- .description("Read THIS repo on your machine and build its trail — no GitHub App, works on private repos")
- .argument("[dir]", "target repo directory", ".")
- .option("--no-approve", "leave the mined rules as drafts for review")
- .option("--no-watch", "return as soon as the push is sent, without following the build")
- .option("--verbose", "print each step's counts and every build stage as it finishes")
- .action(async (dir: string, opts: { approve?: boolean; watch?: boolean; verbose?: boolean }) => {
- const repo = resolve(dir);
- const tty = Boolean(process.stderr.isTTY);
- const verbose = opts.verbose === true;
- // Resolved before the link, because an unlinked repo now signs up for a
- // trail and Trail creates that trail 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);
- // Set when this run opened the browser, which then sits on Trail's build
- // page: the closing lines point at that tab instead of printing a new link.
- let browserOpen = false;
- if (!link && process.env[AUTOPUSH_CHILD_ENV]) {
- // Started in the background by the session-start hook, which only does so
- // for a repo with a trail. The link has gone since (a disconnect in the
- // same moment): signing up would open a browser nobody asked for, so stop.
- console.error("· background push skipped — this repo no longer has a trail attached");
- return;
- }
- if (!link) {
- if (!here) {
- console.error(`✗ this directory has no GitHub origin remote — ${brand()} can only push a GitHub repository today`);
- process.exitCode = 1;
- return;
- }
- const signedUp = await signUpForBrain(repo, `${here.owner}/${here.name}`);
- if (!signedUp) {
- if (!process.exitCode) process.exitCode = 1;
- return;
- }
- link = signedUp;
- browserOpen = true;
- }
- // What the website said this trail is for. Checked BEFORE any reading, so
- // standing in the wrong checkout costs a message rather than a trail full
- // of another repository's rules — a mistake that is silent afterwards,
- // because the rules look perfectly plausible, just not about your code.
- const expected = await fetchExpectedRepo(link);
- if (expected && here && !sameRepo(expected.slug, `${here.owner}/${here.name}`)) {
- console.error(`✗ this trail is for ${expected.slug}, but you are in ${here.owner}/${here.name}`);
- console.error(` cd into ${expected.slug} and run this again, or attach a different trail here.`);
- process.exitCode = 1;
- return;
- }
- const ctx = pushContext(repo);
- if (!ctx) {
- console.error(`✗ this directory has no GitHub origin remote — ${brand()} can only push a GitHub repository today`);
- process.exitCode = 1;
- return;
- }
- const firstPush = !expected || expected.ruleCount === 0;
-
- // The instruction files and the newest pull requests go first, when the
- // trail takes them: its suggestions start from those while the rest of the
- // history is still being read here. In the background, from here on — the
- // picker, the graph build and the full read all happen while it goes, and
- // the full read reuses every GitHub request it made.
- let early: Promise<void> = Promise.resolve();
- if (expected?.earlyUpload) {
- early = (async () => {
- const first = await buildEarlyDigest(repo, { context: ctx });
- if (!first) return;
- const ok = await pushEarlyDigest(link!, first.digest, fetch, { gzip: expected.gzipUpload });
- if (ok && verbose) console.error("· sent the instruction files and the newest pull requests first, so suggestions start now");
- })().catch(() => undefined);
- }
-
- // A repo graft was never set up in gets `graft init` first. Same picker as
- // init: it is how someone agrees to what gets written, so a
- // non-interactive push only says what to run.
- if (wiredHostIds(repo).length === 0) {
- if (process.stdin.isTTY && tty) {
- console.error(`· ${brand()} isn't set up here yet — pick the agents your team uses:`);
- await runInitCommand(
- repo,
- { build: true, mcp: true, hooks: true, statusline: true, global: true, verbose },
- { epilogue: false, push: !verbose },
- );
- } else {
- console.error(`· ${brand()} isn't set up here — run ${cmd("graft init")} so your agents read these rules`);
- }
- }
-
- // The graph is what symbol anchors are resolved against, so a rule mined
- // here can later go stale on its own. Without one the ingest still works;
- // its rules simply govern the repo rather than a symbol in it.
- const graph = loadGraphCached(contextDirFor(repo, program.opts<GlobalOpts>().dir));
- if (!graph) console.error(`· no graph yet — run ${cmd("graft build")} so rules can be anchored to symbols`);
- const reading = startSpinner(`reading ${ctx.owner}/${ctx.name} · commits, pull-request discussion and the docs in the tree`);
- const built = await buildLocalDigest(repo, graph, { autoApprove: opts.approve !== false, context: ctx });
- if ("error" in built) {
- reading.stop();
- console.error(`✗ ${built.error}`);
- process.exitCode = 1;
- return;
- }
- const d = built.digest;
- reading.update("sending it to Trail");
- await early;
- const sent = await pushDigest(link, d, fetch, uploadCaps(expected));
- reading.stop();
- if (built.warning) console.error(`⚠ ${built.warning}`);
- if ("error" in sent) {
- console.error(`✗ ${sent.error}`);
- process.exitCode = 1;
- return;
- }
- // What the session-start hook's background refresh compares HEAD against:
- // a push of history Trail already has would mine the same rules again.
- recordTrailPush(repo, ctx.headSha);
- const fmt = (x: number) => x.toLocaleString("en-US");
- const trailLabel = expected?.brainName ? `“${expected.brainName}”` : `${d.owner}/${d.name}`;
- console.error(
- `✓ sent ${fmt(d.commits.length)} commits and ${fmt(d.threads.length)} discussions to ${trailLabel} · no file contents left this machine`,
- );
- if (verbose) console.error(` ${fmt(d.symbols.length)} symbols, ${fmt(d.sources.length)} stated sources`);
-
- const buildPage = brainUrl(link.brainId);
- // Held rather than handed back. Everything above this line succeeded even
- // in the runs that end badly: the push lands, and then the miner fails —
- // which is where roughly a third of production's repo trails die. Returning
- // the prompt here is what made that invisible from this side, on CI and
- // over SSH permanently so. `--no-watch` is for a caller that genuinely
- // wants fire-and-forget.
- if (opts.watch === false) {
- console.error("· building now — the rules reach this repo on their own; watch it at");
- console.error(` ${buildPage}`);
- return;
- }
-
- const live = tty && !verbose;
- if (!live) console.error("· building the trail");
- const spinner = live ? startSpinner("building the trail · reaching the repository · Ctrl-C detaches") : null;
- let last: RepoState | null = null;
- // Ctrl-C detaches: the work is server-side, and killing a watcher must
- // never look like killing the build.
- const onSigint = () => {
- spinner?.stop();
- console.error("· detached — the build keeps going; watch it at");
- console.error(` ${buildPage}`);
- process.exit(130);
- };
- process.once("SIGINT", onSigint);
- const outcome = await watchBuild(link, {
- events: expected?.events === true,
- stageLines: !live,
- write: (line) => (spinner ? spinner.print(line) : console.error(line)),
- onState: (view, repoState) => {
- last = repoState;
- spinner?.update(`building the trail · ${DOING_LABEL[currentStage(view)]} · Ctrl-C detaches`);
- },
- });
- process.off("SIGINT", onSigint);
- spinner?.stop();
-
- const ruleCount = rulesSoFar(last);
- const rules = `${fmt(ruleCount)} rule${ruleCount === 1 ? "" : "s"}`;
- const wired = [...new Set([...(readStamp(repo)?.hosts ?? []), ...wiredHostIds(repo)])];
- const closing = () => {
- const line = suggestionsLine((last as RepoState | null)?.suggestions, wired, !firstPush);
- if (!line) return;
- if (browserOpen) {
- console.error(`${line} — they are in the Trail tab in your browser`);
- console.error(` ${reviewUrl(link!.brainId)}`);
- } else {
- console.error(line);
- console.error(` review: ${reviewUrl(link!.brainId)}`);
- }
- };
- if (outcome === "completed") {
- console.error(`✓ trail built · ${rules}, reaching this repo on their own`);
- closing();
- return;
- }
- // The ordinary ending for anything but a small repository. The history is
- // mined in slices, and the prompt comes back on the first of them: mining is
- // the part that fails and it has now succeeded, and the rest is filing,
- // which is minutes of reliable work nobody gains by watching.
- if (outcome === "building") {
- console.error(
- firstPush
- ? `✓ trail has its first ${rules} · they reach this repo on their own`
- : `✓ trail updated · ${rules}, reaching this repo on their own`,
- );
- closing();
- return;
- }
- if (outcome === "failed") {
- // A non-zero exit, unlike every other ending here: this is the one case
- // where the work did not produce a trail, and a CI step that ran the push
- // should hear about it the way it hears about any other failure. The
- // watcher has already printed where it stopped and why.
- process.exitCode = 1;
- return;
- }
- if (outcome === "unreachable") {
- console.error("· lost touch with Trail — the build keeps going; watch it at the link below");
- } else {
- console.error("· still building after 15 minutes — not failed, just long; watch it at the link below");
- }
- console.error(` ${buildPage}`);
- });
-}
-
-// `graft claude-md pull` is `graft trail pull` now: the CLAUDE.md changes are
-// the first half of what that writes. Kept so the old name keeps working, but
-// hidden from --help so people only ever see one pull command.
-const claudeMd = program
- .command("claude-md", { hidden: true })
- .description("The CLAUDE.md changes this repo's trail suggested (now part of graft trail pull)");
-
-claudeMd
- .command("pull")
- .description("Same as graft trail pull: write every change you accepted in Trail into this repo")
- .argument("[dir]", "target repo directory", ".")
- .option("--dry-run", "show what would change without writing anything or telling Trail")
- .action(async (dir: string, opts: { dryRun?: boolean }) => {
- console.error(`· ${brand()} claude-md pull is now part of ${cmd("graft trail pull")} — running that`);
- await runTrailPullCommand(dir, opts);
- });
-
-function brainStatusCommand(name = "status"): Command {
- return new Command(name)
- .description("Show the attached brain, how many rules are cached, and how many still match the code")
- .argument("[dir]", "target repo directory", ".")
- .option("--json", "machine-readable output")
- .action((dir: string, opts: { json?: boolean }) => {
- const repo = resolve(dir);
- const { link, rules, fetchedAt } = brainStatus(repo);
- // Resolve every cached rule against the CURRENT graph, so the count of stale
- // rules is the real one rather than what was true at pull time. This is the
- // number worth surfacing: it says how far the codebase has drifted from what
- // the team decided.
- const graph = loadGraphCached(contextDirFor(repo, program.opts<GlobalOpts>().dir));
- const applied = rulesForPointers(
- (graph?.nodes ?? []).map((n) => `${n.path}:${n.span}`),
- rules,
- graph,
- );
- if (opts.json) {
- console.log(JSON.stringify({ brainId: link?.brainId ?? null, cached: rules.length, fetchedAt, anchored: applied.length, stale: applied.filter((a) => a.stale).length }, null, 2));
- return;
- }
- if (!link) {
- console.error(`· no brain attached — run \`${cmd("graft trail connect")} <brainId>:<token>\``);
- return;
- }
- console.error(`brain ${link.brainId}`);
- console.error(` ${rules.length} rule(s) cached${fetchedAt ? `, pulled ${new Date(fetchedAt).toISOString()}` : ""}`);
- if (!graph) {
- console.error(` no graph yet — run \`${cmd("graft build")}\` to see which rules still match the code`);
- return;
- }
- const stale = applied.filter((a) => a.stale);
- console.error(` ${applied.length} anchored to symbols in this repo`);
- console.error(
- stale.length
- ? ` ${stale.length} describe code that has changed since:`
- : " none describe code that has changed since",
- );
- for (const a of stale.slice(0, 10)) console.error(` - ${a.rule}\n ${a.pointer}`);
- });
-}
-
-function disconnectCommand(name = "disconnect"): Command {
- return new Command(name)
- .description("Forget the attached brain (its rules stay in the instruction files until the next init)")
- .argument("[dir]", "target repo directory", ".")
- .action((dir: string) => {
- const repo = resolve(dir);
- clearLink(resolve(dir));
- console.error(`✓ detached the brain from ${repo}`);
- });
-}
-
/* -------------------------------------------------------------------------- */
/* trail login · logout · workspace */
/* -------------------------------------------------------------------------- */
@@ -2841,7 +2186,7 @@ function shortCount(n: number): string {
}
/**
- * `trail status`: what was `graft stats` and `graft trail status`, on one
+ * `trail status`: what was `graft stats`, on one
* screen. The code map and whether it matches the code, the learnings for
* this repo, the workspace, and what the agents saved this week.
*/
@@ -2862,9 +2207,6 @@ function statusCommand(name = "status"): Command {
const personal = all.filter((n) => n.scope === "personal").length;
const cloud = readCloud();
const shared = cloud ? inWorkspace(repo, cloud) : false;
- const { link, rules } = brainStatus(repo);
- const anchored = link && graph ? rulesForPointers(graph.nodes.map((n) => `${n.path}:${n.span}`), rules, graph) : [];
- const matching = anchored.filter((a) => !a.stale).length;
const saved = savedThisWeek(repo);
if (opts.json) {
@@ -2874,7 +2216,6 @@ function statusCommand(name = "status"): Command {
codeMap: graph ? { nodes: graph.meta.nodeCount, inSync: fresh } : null,
learnings: kept ? { repo: inRepo, branches: onBranches, personal } : null,
workspace: cloud ? { name: cloud.workspace.name, url: cloud.workspace.url, repos: cloud.repos.length, thisRepo: shared } : null,
- rules: link ? { brainId: link.brainId, cached: rules.length, anchored: anchored.length, matching } : null,
week: { savedTokens: saved },
},
null,
@@ -2901,34 +2242,18 @@ function statusCommand(name = "status"): Command {
"workspace",
`${cloud.workspace.name} · ${cloud.repos.length} repo${cloud.repos.length === 1 ? "" : "s"}${shared ? ", this one included" : `, not this one (${cmd("graft workspace add")})`} · ${cloud.workspace.url}`,
);
- if (link)
- row("rules", `${fmt(rules.length)} cached from Trail` + (graph && anchored.length ? `, ${fmt(matching)} of ${fmt(anchored.length)} anchored still match the code` : ""));
row("this week", saved > 0 ? `~${shortCount(saved)} tokens saved` : "nothing saved yet");
});
}
if (TRAIL) {
- // The old `graft trail …` group, at the top level: `trail push`, `trail
- // login`. `connect` and `watch` still run, unlisted — connect so the
- // handoff links Trail already sent keep working.
for (const c of [teamCheckCommand(), teamCommand()]) program.addCommand(c.helpGroup(GROUP.memory));
// Signing in waits until it gives a team more than committing .trail/ does.
for (const c of [workspaceCommand(), loginCommand(), logoutCommand()]) program.addCommand(c.helpGroup(GROUP.cloud), { hidden: !cloudEnabled() });
- // The brain's rules (`trail push`, `trail pull`) still run, unlisted: a
- // workspace is how a team shares now.
- program.addCommand(pushCommand(), { hidden: true });
- program.addCommand(pullCommand(), { hidden: true });
- program.addCommand(connectCommand(), { hidden: true });
- program.addCommand(watchCommand(), { hidden: true });
program.addCommand(statusCommand().helpGroup(GROUP.setup));
- // `trail trail push` and the rest, for fingers that learned graft.
- const habit = program.command("trail", { hidden: true }).description("The old graft trail … commands");
- for (const c of [connectCommand(), pullCommand(), watchCommand(), pushCommand(), statusCommand(), disconnectCommand()])
- habit.addCommand(c);
-
// Help lists the groups in this order, and the commands within each.
- const order = ["ask", "grep", "skeleton", "callers", "map", "note", "check", "team", "learn", "skills", "init", "build", "status", "upgrade", "uninstall", "telemetry", "workspace", "login", "logout", "push", "pull", "blast"];
+ const order = ["ask", "grep", "skeleton", "callers", "map", "note", "check", "team", "learn", "skills", "init", "build", "status", "upgrade", "uninstall", "telemetry", "workspace", "login", "logout", "blast"];
const rank = (c: Command) => {
const i = order.indexOf(c.name());
return i === -1 ? order.length : i;
@@ -2960,16 +2285,9 @@ if (TRAIL) {
};
for (const c of program.commands) if (summaries[c.name()]) c.summary(summaries[c.name()]!);
program.addHelpText("after", "\ntrail <command> --help for flags · every graft command still works");
-} else {
- // `graft trail …` still works: see legacy-args.ts.
- const brain = program
- .command("trail")
- .description("The Trail attached to this repo: the rules mined from its own history");
- for (const c of [connectCommand(), pullCommand(), watchCommand(), pushCommand(), brainStatusCommand(), disconnectCommand()])
- brain.addCommand(c);
}
-program.parseAsync(withLegacyNames(process.argv)).catch((err) => {
+program.parseAsync(process.argv).catch((err) => {
console.error(err instanceof Error ? err.message : err);
process.exit(1);
});
diff --git a/src/legacy-args.ts b/src/legacy-args.ts
deleted file mode 100644
index 00bd4aa0..00000000
--- a/src/legacy-args.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * The old spellings of renamed commands, still accepted.
- *
- * `graft brain …` became `graft trail …`, and `init --brain` became
- * `init --trail`, to match the product's name. The old ones are in docs, in
- * scripts, in shell history and on Trail pages already open in someone's
- * browser, so they keep working. They are rewritten before parsing rather than
- * registered as aliases, so help lists only the new names.
- */
-
-/** Global options that take a value: their value is never the command. */
-const VALUE_OPTIONS = new Set(["--dir", "--provider", "--model", "--api-key", "--base-url"]);
-
-/** `process.argv` with the old spellings replaced by the new ones. */
-export function withLegacyNames(argv: readonly string[]): string[] {
- const out = [...argv];
- // The command is the first word after the global options.
- for (let i = 2; i < out.length; i++) {
- const a = out[i]!;
- if (a === "--") break;
- if (a.startsWith("-")) {
- if (VALUE_OPTIONS.has(a)) i++;
- continue;
- }
- if (a === "brain") out[i] = "trail";
- break;
- }
- return out.map((a) => (a === "--brain" ? "--trail" : a.startsWith("--brain=") ? `--trail=${a.slice("--brain=".length)}` : a));
-}
diff --git a/src/telemetry/contract.ts b/src/telemetry/contract.ts
index 0bd95276..0251ef10 100644
--- a/src/telemetry/contract.ts
+++ b/src/telemetry/contract.ts
@@ -51,29 +51,13 @@ export const EVENTS: Record<string, ReadonlySet<string>> = {
build_failed: new Set<string>(['stage', 'code']),
/** One query, from any surface. The DAU backbone and the dead-command detector. */
query: new Set<string>(['command', 'surface', 'hit', 'notes']),
- /** `graft trail push` in a repo with no brain, sending the user to Trail to
- * make one. Queued the moment the link is printed, so a signup somebody
- * walked away from is still counted — the settle below never fires for those,
- * and abandonment is exactly the thing a terminal handoff loses silently. */
+ /** A trail command handing the agent a sign-in link to pass on. Queued the
+ * moment the link is printed, so a sign-in somebody walked away from is still
+ * counted — the settle below never fires for those. */
brain_signup_opened: new Set<string>(['mode', 'command', 'wording']),
/** That handoff reaching an end. `outcome` is a closed set, so the reason a
* signup failed travels as a category and never as the error's own words. */
brain_signup_settled: new Set<string>(['outcome', 'mode', 'duration_bucket']),
- /** `graft trail pull` reaching an end: whether accepted Trail suggestions
- * made it into this checkout. `kinds` is which kinds of context file were
- * written (a fixed set, sorted); every count is a bucket. Paths, headings and
- * the changes' text never travel. The adoption number for Trail's context
- * files: how many people actually take a suggestion home. */
- trail_pulled: new Set<string>(['outcome', 'kinds', 'files_bucket', 'changes_bucket', 'skipped_bucket', 'suggested_bucket']),
- /** `graft trail watch` ending. `reason` is a closed set (TRAIL_WATCH_REASONS);
- * the counts it ended on and how long it waited are buckets. Whether the
- * watcher that replaced the agent-written polling loop actually ends on
- * something worth relaying, or mostly times out. */
- trail_watch_exit: new Set<string>(['reason', 'suggested_bucket', 'accepted_bucket', 'duration_bucket']),
- /** The session-start hook's background `graft trail push`: `started`, or
- * `skipped` with a `reason` from a closed set (TRAIL_AUTOPUSH_SKIPS). Only for
- * a repo with a trail attached — every other repo sends nothing. */
- trail_autopush: new Set<string>(['outcome', 'reason']),
/** `trail note` saved a session note (into `~/.trail/`). Whether it carries
* a cost, and how many files it is about, as a bucket. The title, the text
* and the paths never travel. The supply side of the notes loop; the
@@ -155,7 +139,7 @@ export function isTrackedCommand(name: string): name is TrackedCommand {
}
/**
- * How a `graft trail push` signup ended.
+ * How a sign-in handoff ended.
*
* Five categories and nothing else, because the alternative — the error string
* the CLI already prints — carries a repo slug and a URL. `timed_out` and
@@ -168,26 +152,6 @@ export function isTrackedCommand(name: string): name is TrackedCommand {
export const BRAIN_SIGNUP_OUTCOMES = ['linked', 'timed_out', 'no_tty', 'bad_callback', 'stopped'] as const;
export type BrainSignupOutcome = (typeof BRAIN_SIGNUP_OUTCOMES)[number];
-/**
- * How a `graft trail pull` ended. `written`: at least one file changed.
- * `already_present`: everything accepted was already in the files.
- * `nothing_accepted`: Trail had nothing accepted for this repo's agents.
- * `skipped`: accepted changes existed but none could be applied (the local
- * file moved on). `error`: Trail could not be read or a file not written.
- * `dry_run`: `--dry-run`, nothing written.
- */
-export const TRAIL_PULL_OUTCOMES = ['written', 'already_present', 'nothing_accepted', 'skipped', 'error', 'dry_run'] as const;
-export type TrailPullOutcome = (typeof TRAIL_PULL_OUTCOMES)[number];
-
-/** How `graft trail watch` ended — see WatchExitReason in brain/watch-trail.ts. */
-export const TRAIL_WATCH_REASONS = ['suggestions', 'accepted', 'timeout', 'refused', 'no_trail'] as const;
-
-/** Why a background push did not start. `no_trail` is never sent. */
-export const TRAIL_AUTOPUSH_SKIPS = ['disabled', 'no_head', 'head_unchanged', 'throttled', 'spawn_failed'] as const;
-
-/** The context-file kinds `trail_pulled.kinds` may name; anything else is dropped. */
-export const CONTEXT_FILE_KINDS = ['claude_md', 'folder_claude_md', 'agents_md', 'cursor_rule', 'skill'] as const;
-
/** Where a failing build died. Coarse on purpose: enough to route a bug, not
* enough to describe anyone's repo. */
export const BUILD_STAGES = ['walk', 'extract', 'graph', 'summarize', 'synthesize', 'write'] as const;
diff --git a/src/upkeep-run.ts b/src/upkeep-run.ts
index 2742fe96..4699c614 100644
--- a/src/upkeep-run.ts
+++ b/src/upkeep-run.ts
@@ -15,7 +15,6 @@ import { ensureRepoTrail } from './notes/repo-trail.js';
import {
formatUpdateNudge,
formatWiringRefresh,
- maybeRefreshBrainRules,
maybeRefreshInBackground,
readUpdateCache,
reconcileWiring,
@@ -111,11 +110,6 @@ export function runUpkeep(
const refreshLine = formatWiringRefresh(refreshed);
if (refreshLine) lines.push(refreshLine);
} catch { /* fail-soft: wiring refresh is never worth breaking a session for */ }
- try {
- // Rules the attached brain has gained since the last pull. Detached, so it
- // never delays the session it runs in.
- if (opts.background !== false) maybeRefreshBrainRules(repo);
- } catch { /* same */ }
try {
if (opts.background !== false) maybeRefreshInBackground(opts.home);
const nudge = formatUpdateNudge(current, readUpdateCache(opts.home)?.latest);
diff --git a/src/upkeep.ts b/src/upkeep.ts
index 7305c151..206c2ac6 100644
--- a/src/upkeep.ts
+++ b/src/upkeep.ts
@@ -33,7 +33,6 @@ import { HOSTS } from './hosts/registry.js';
import { START } from './hosts/sections.js';
import { getNpmViewVersion, readCurrentVersion } from './cli-meta.js';
import { brand } from './brand.js';
-import { cacheIsStale, markRulesChecked, readLink, readRulesCache } from './brain/link.js';
import { graftCliPath } from './claude/paths.js';
/**
@@ -145,41 +144,6 @@ export function maybeRefreshInBackground(home?: string, now = Date.now()): boole
}
}
-/**
- * Refresh the attached brain's rules in a detached child, when they are stale.
- *
- * The same shape as the update check above, and for the same reason: this runs
- * inside session-start hooks and MCP boot, where waiting on the network is a
- * stalled first turn. So nothing here blocks — the child does the fetch and
- * this call returns immediately.
- *
- * Without it a brain is pulled exactly once, at `graft trail connect`, and
- * never again. That was survivable when connecting happened after the brain
- * finished building; it is not survivable now that onboarding connects DURING
- * the build, because the one pull returns an empty rulebook and nothing would
- * ever go back for the real one.
- *
- * The attempt is stamped before spawning, so a brain that is still building
- * costs one request per TTL window rather than one per command.
- */
-export function maybeRefreshBrainRules(repo: string, now = Date.now()): boolean {
- try {
- if (!readLink(repo)) return false;
- const cache = readRulesCache(repo);
- if (!cacheIsStale(cache, now)) return false;
- markRulesChecked(repo, now);
- const child = spawn(process.execPath, [graftCliPath(), '_brain-refresh', repo], {
- detached: true,
- stdio: 'ignore',
- windowsHide: true,
- });
- child.unref();
- return true;
- } catch {
- return false; // no spawn, or an unreadable repo — the cached rules still serve
- }
-}
-
/** One line, or nothing. Nothing is the common case — don't spend context on
* "you're up to date". */
export function formatUpdateNudge(current: string, latest: string | null | undefined): string | null {
diff --git a/src/util/browser.ts b/src/util/browser.ts
new file mode 100644
index 00000000..b715b9b2
--- /dev/null
+++ b/src/util/browser.ts
@@ -0,0 +1,12 @@
+import { spawn } from "node:child_process";
+
+/** Open `url` in the default browser. Best-effort: the printed URL is the fallback. */
+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/util/state.ts b/src/util/state.ts
index 403c75af..0730a3a0 100644
--- a/src/util/state.ts
+++ b/src/util/state.ts
@@ -104,19 +104,6 @@ export interface BuildConfig {
* checkout someone parked in the tree. Absent/false keeps the historical
* boundary. */
followNestedRepos?: boolean;
- /** The Trail brain this repo's rules come from: the brain id and the token to
- * read it with. Persisted here — in the git-ignored `.graft/` — rather than in
- * `~/.graft/`, because a brain belongs to one repository and two checkouts on
- * one machine must not share one. `undefined` clears it. */
- brain?: { brainId: string; token: string; baseUrl?: string };
- /** A sign-up an agent-run `graft trail push` opened and has not collected
- * yet: the state in its link, and which repository it was for. Cleared once
- * collected. `undefined` clears it. */
- pendingSignup?: { state: string; repo: string; createdAt: number };
- /** `false` turns off the once-a-day background `graft trail push` the
- * session-start hook starts for a repo with a trail (see brain/autopush.ts).
- * Absent means on. GRAFT_TRAIL_AUTOPUSH=0 does the same for every repo. */
- trailAutoPush?: boolean;
}
/** Local, Git-ignored repository configuration. Kept outside generated
diff --git a/test/brain-context-files-pull.test.ts b/test/brain-context-files-pull.test.ts
deleted file mode 100644
index c38cf8a7..00000000
--- a/test/brain-context-files-pull.test.ts
+++ /dev/null
@@ -1,261 +0,0 @@
-/**
- * `graft trail pull` writes accepted changes into every context file, not only
- * the root CLAUDE.md. It edits files people also edit by hand, so the tests are
- * about restraint: a whole-file change never overwrites someone's file, a
- * replace only lands on the file it was computed against, a path from Trail
- * never escapes the repo, and files for agents nobody picked are left alone.
- */
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
-import { dirname, join } from 'node:path';
-import { planContextFile, readByWired, safeRelPath, writePlannedFile, type ContextFile } from '../src/brain/context-files.js';
-import { runTrailPull } from '../src/brain/pull.js';
-import type { BrainLink } from '../src/brain/link.js';
-import { tmpRepo } from './helpers.js';
-
-function put(root: string, rel: string, text: string): void {
- mkdirSync(dirname(join(root, rel)), { recursive: true });
- writeFileSync(join(root, rel), text);
-}
-
-const AGENTS = ['# api', '', '## Commands', '', '- `make test` runs the unit tests.', '', '## Style', '', '- gofmt everything.', ''].join('\n');
-
-test('edit and add patch the file exactly as the CLAUDE.md pull does', () => {
- const root = tmpRepo('ctx-edit');
- put(root, 'services/api/AGENTS.md', AGENTS);
- const plan = planContextFile(root, {
- kind: 'agents_md',
- path: 'services/api/AGENTS.md',
- changes: [
- { id: 'e1', kind: 'edit', heading: 'Commands', find: '- `make test` runs the unit tests.', text: '- `make test` runs unit and integration tests.' },
- { id: 'a1', kind: 'add', heading: 'Money', after_heading: 'Commands', text: 'Amounts are integer cents.' },
- ],
- });
- assert.equal(plan.status, 'M');
- assert.deepEqual(plan.written.map((c) => c.id), ['e1', 'a1']);
- assert.match(plan.text!, /## Commands\n\n- `make test` runs unit and integration tests\.\n\n## Money\n\nAmounts are integer cents\.\n\n## Style/);
- assert.match(plan.text!, /- gofmt everything\./, 'untouched sections come back as they were');
-});
-
-test('create writes a new file, folders and all', () => {
- const root = tmpRepo('ctx-create');
- const plan = planContextFile(root, {
- kind: 'cursor_rule',
- path: '.cursor/rules/money.mdc',
- changes: [{ id: 'c1', kind: 'create', text: '---\ndescription: money\n---\nAmounts are integer cents.' }],
- });
- assert.equal(plan.status, 'A');
- writePlannedFile(root, plan);
- assert.equal(readFileSync(join(root, '.cursor/rules/money.mdc'), 'utf8'), '---\ndescription: money\n---\nAmounts are integer cents.\n');
-});
-
-test('create over an identical file counts as applied and writes nothing', () => {
- const root = tmpRepo('ctx-same');
- put(root, 'web/CLAUDE.md', '# web\r\n\r\nPascalCase components.\r\n');
- const plan = planContextFile(root, {
- kind: 'folder_claude_md',
- path: 'web/CLAUDE.md',
- changes: [{ id: 'c2', kind: 'create', text: '# web\n\nPascalCase components.' }],
- });
- assert.equal(plan.status, '');
- assert.deepEqual(plan.present.map((c) => c.id), ['c2']);
-});
-
-test('create over a different file is a conflict, and the file is left alone', () => {
- const root = tmpRepo('ctx-conflict');
- put(root, 'web/CLAUDE.md', '# web\n\nOurs.\n');
- const plan = planContextFile(root, {
- kind: 'folder_claude_md',
- path: 'web/CLAUDE.md',
- changes: [{ id: 'c3', kind: 'create', text: '# web\n\nTheirs.\n' }],
- });
- assert.equal(plan.status, '');
- assert.equal(plan.skipped.length, 1);
- assert.match(plan.skipped[0].why, /other content/);
-});
-
-test('create over a file graft owns replaces it', () => {
- const root = tmpRepo('ctx-managed');
- put(root, '.cursor/rules/graft.mdc', 'old graft rule\n');
- const plan = planContextFile(root, {
- kind: 'cursor_rule',
- path: '.cursor/rules/graft.mdc',
- managed_by_graft: true,
- changes: [{ id: 'c4', kind: 'create', text: 'new graft rule\n' }],
- });
- assert.equal(plan.status, 'M');
- assert.equal(plan.text, 'new graft rule\n');
-});
-
-test('replace lands only on the file it was computed against', () => {
- const root = tmpRepo('ctx-replace');
- put(root, '.cursor/rules/style.mdc', 'Use tabs.\r\n');
- const change = { id: 'r1', kind: 'replace' as const, find: 'Use tabs.\n', text: 'Use two spaces.\n' };
- const ok = planContextFile(root, { kind: 'cursor_rule', path: '.cursor/rules/style.mdc', changes: [change] });
- assert.equal(ok.status, 'M');
- assert.equal(ok.text, 'Use two spaces.\n');
-
- put(root, '.cursor/rules/style.mdc', 'Use tabs. And semicolons.\n');
- const moved = planContextFile(root, { kind: 'cursor_rule', path: '.cursor/rules/style.mdc', changes: [change] });
- assert.equal(moved.status, '');
- assert.match(moved.skipped[0].why, /changed here since Trail read it/);
-
- put(root, '.cursor/rules/style.mdc', 'Use two spaces.\n');
- const done = planContextFile(root, { kind: 'cursor_rule', path: '.cursor/rules/style.mdc', changes: [change] });
- assert.deepEqual(done.present.map((c) => c.id), ['r1']);
-});
-
-test('an edit to a file that is not here yet creates it', () => {
- const root = tmpRepo('ctx-missing');
- const plan = planContextFile(root, {
- kind: 'folder_claude_md',
- path: 'web/CLAUDE.md',
- changes: [{ id: 'e2', kind: 'edit', heading: 'Frontend', find: '', text: 'Components are PascalCase.' }],
- });
- assert.equal(plan.status, 'A');
- assert.equal(plan.text, '## Frontend\n\nComponents are PascalCase.\n');
-});
-
-test('a path from Trail never leaves the repo', () => {
- const root = tmpRepo('ctx-safe');
- for (const bad of ['../outside.md', '/etc/passwd', 'a/../../b.md', '.git/config', 'C:/x.md', '']) {
- assert.equal(safeRelPath(root, bad), null, bad);
- }
- assert.equal(safeRelPath(root, 'web/CLAUDE.md'), 'web/CLAUDE.md');
- const plan = planContextFile(root, { kind: 'agents_md', path: '../AGENTS.md', changes: [{ id: 'x', kind: 'create', text: 'x' }] });
- assert.equal(plan.status, '');
- assert.equal(plan.skipped.length, 1);
-});
-
-test('files are only for the agents that were picked', () => {
- assert.equal(readByWired('cursor_rule', ['claude']), false);
- assert.equal(readByWired('agents_md', ['claude', 'agents']), true);
- assert.equal(readByWired('skill', ['claude']), true);
- assert.equal(readByWired('cursor_rule', []), true, 'nothing wired means no choice to respect');
-});
-
-// --- the whole pull, against a fake Trail ---------------------------------------
-
-const link = { brainId: 'b1', token: 'gbt_1.x', baseUrl: 'http://trail.test' } as unknown as BrainLink;
-const json = (body: unknown, status = 200) =>
- new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
-
-function fakeTrail(files: ContextFile[], opts: { contextFiles?: 'ok' | 'missing'; repo?: unknown; claudeMd?: unknown[] } = {}) {
- const applied: Record<string, string[]> = {};
- const f = (async (u: string, init?: RequestInit) => {
- const path = new URL(u).pathname;
- if (path.endsWith('/rules/anchors')) return json({ anchors: [] });
- if (path.endsWith('/claude-md')) {
- return json({ path: 'CLAUDE.md', head_sha: 'abc', changes: opts.claudeMd ?? [{ id: 'm1', kind: 'add', heading: 'Money', after_heading: '', text: 'Integer cents.' }] });
- }
- if (path.endsWith('/repo') && opts.repo) return json(opts.repo);
- if (path.endsWith('/context-files')) {
- return opts.contextFiles === 'missing' ? json({ error: 'not found' }, 404) : json({ head_sha: 'abc', files });
- }
- if (path.endsWith('/applied')) {
- applied[path] = (JSON.parse(String(init?.body)) as { ids: string[] }).ids;
- return json({ applied: 1 });
- }
- return json({ error: 'unexpected' }, 500);
- }) as typeof fetch;
- return { f, applied };
-}
-
-test('a pull writes the CLAUDE.md changes, then every other file, and tells Trail which', async () => {
- const root = tmpRepo('ctx-pull');
- put(root, 'CLAUDE.md', '# app\n\n## Commands\n\n- `npm test`\n');
- put(root, 'web/CLAUDE.md', '# web\n\nOurs.\n');
- const { f, applied } = fakeTrail([
- { kind: 'agents_md', path: 'AGENTS.md', changes: [{ id: 'g1', kind: 'create', text: '# agents\n\nInteger cents.\n' }] },
- { kind: 'folder_claude_md', path: 'web/CLAUDE.md', changes: [{ id: 'w1', kind: 'create', text: '# web\n\nTheirs.\n' }] },
- { kind: 'cursor_rule', path: '.cursor/rules/money.mdc', changes: [{ id: 'k1', kind: 'create', text: 'cents\n' }] },
- ]);
- const lines: string[] = [];
- const code = await runTrailPull(root, link, { home: root, wired: ['claude', 'agents'], fetchImpl: f, write: (l) => lines.push(l) });
- const out = lines.join('\n');
-
- assert.equal(code, 1, 'the conflict makes it exit non-zero, as claude-md pull did');
- assert.match(out, /✓ wrote 2 accepted changes/);
- assert.match(out, / M CLAUDE\.md +\+ Money/);
- assert.match(out, / A AGENTS\.md/);
- assert.match(out, /⚠ skipped web\/CLAUDE\.md — a file with other content is already there; edit it in Trail, then pull again/);
- assert.doesNotMatch(out, /money\.mdc/, 'cursor was not picked, so its rule is neither listed nor written');
- assert.match(out, /review with git diff, then commit/);
-
- assert.match(readFileSync(join(root, 'CLAUDE.md'), 'utf8'), /## Money\n\nInteger cents\./);
- assert.equal(readFileSync(join(root, 'AGENTS.md'), 'utf8'), '# agents\n\nInteger cents.\n');
- assert.equal(readFileSync(join(root, 'web/CLAUDE.md'), 'utf8'), '# web\n\nOurs.\n');
- assert.ok(!existsSync(join(root, '.cursor/rules/money.mdc')));
-
- assert.deepEqual(applied['/api/public/brains/b1/claude-md/applied'], ['m1']);
- assert.deepEqual(applied['/api/public/brains/b1/context-files/applied'], ['g1'], 'only what was written, never the conflict');
-});
-
-test('a dry run writes nothing and tells Trail nothing', async () => {
- const root = tmpRepo('ctx-dry');
- const { f, applied } = fakeTrail([
- { kind: 'agents_md', path: 'AGENTS.md', changes: [{ id: 'g1', kind: 'create', text: 'x\n' }] },
- ]);
- const lines: string[] = [];
- await runTrailPull(root, link, { home: root, wired: [], dryRun: true, fetchImpl: f, write: (l) => lines.push(l) });
- assert.match(lines.join('\n'), /✓ would write 2 accepted changes/);
- assert.match(lines.join('\n'), /dry run — nothing written, and Trail was not told/);
- assert.ok(!existsSync(join(root, 'AGENTS.md')) && !existsSync(join(root, 'CLAUDE.md')));
- assert.deepEqual(applied, {});
-});
-
-test('a Trail without context files still pulls CLAUDE.md, silently', async () => {
- const root = tmpRepo('ctx-older');
- const { f } = fakeTrail([], { contextFiles: 'missing' });
- const lines: string[] = [];
- const code = await runTrailPull(root, link, { home: root, wired: ['claude'], fetchImpl: f, write: (l) => lines.push(l) });
- assert.equal(code, 0);
- assert.match(lines.join('\n'), /✓ wrote 1 accepted change\n A CLAUDE\.md +\+ Money/);
- assert.doesNotMatch(lines.join('\n'), /✗/);
-});
-
-/** Trail's GET /repo mid-review: 3 CLAUDE.md suggestions, 2 skills, 4 Cursor rules. */
-const REVIEWING = {
- repo: { status: 'completed', rule_count: 75 },
- claude_md: { status: 'ready', changes: 3 },
- context_files: true,
- context_files_progress: {
- changes: 6,
- files: [
- { kind: 'skill', path: '.claude/skills/a/SKILL.md', changes: 2 },
- { kind: 'cursor_rule', path: '.cursor/rules/a.mdc', changes: 4 },
- ],
- },
-};
-
-test('with nothing accepted, a pull says how many suggestions are waiting for the wired agents', async () => {
- const root = tmpRepo('ctx-waiting');
- const { f } = fakeTrail([], { repo: REVIEWING, claudeMd: [] });
- const lines: string[] = [];
- const code = await runTrailPull(root, link, { home: root, wired: ['claude'], dryRun: true, fetchImpl: f, write: (l) => lines.push(l) });
- const out = lines.join('\n');
- assert.equal(code, 0);
- assert.match(out, /● 5 suggested so far for the files claude read, none accepted yet\n review: \S+\/brain\/b1\/context-files/);
- assert.doesNotMatch(out, /nothing accepted in Trail yet/);
-});
-
-test('a dry run with accepted changes also says how many were suggested, and where to review', async () => {
- const root = tmpRepo('ctx-waiting-dry');
- const { f } = fakeTrail([], { repo: REVIEWING });
- const lines: string[] = [];
- await runTrailPull(root, link, { home: root, wired: ['claude', 'cursor'], dryRun: true, fetchImpl: f, write: (l) => lines.push(l) });
- const out = lines.join('\n');
- assert.match(out, /✓ would write 1 accepted change/);
- assert.match(out, /● 9 suggested so far for the files claude and cursor read, 1 of them accepted\n review: /);
- assert.match(out, /dry run — nothing written/);
-});
-
-test('a Trail that sends no counts leaves the pull as it was', async () => {
- const root = tmpRepo('ctx-no-counts');
- const { f } = fakeTrail([], { claudeMd: [] });
- const lines: string[] = [];
- await runTrailPull(root, link, { home: root, wired: ['claude'], fetchImpl: f, write: (l) => lines.push(l) });
- assert.match(lines.join('\n'), /· nothing accepted in Trail yet — review:/);
- assert.doesNotMatch(lines.join('\n'), /suggested so far/);
-});
diff --git a/test/brain-early-upload.test.ts b/test/brain-early-upload.test.ts
deleted file mode 100644
index 741efab3..00000000
--- a/test/brain-early-upload.test.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-/**
- * The early upload sends the instruction file and the newest pull requests
- * before the rest of the history, so Trail's first CLAUDE.md suggestions start
- * while the full read is still on this machine. Two things make that safe, and
- * both are tested here: it is only sent to a brain that says it takes it, and
- * the full read does not ask GitHub again for threads the early one read.
- */
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import { fetchExpectedRepo, pushEarlyDigest } from '../src/brain/push.js';
-import { newThreadReadCache, readThreads, THREAD_FETCH_CONCURRENCY, type HistoryThread, type RepoDigest } from '../src/app/history.js';
-import type { BrainLink } from '../src/brain/link.js';
-
-const link = { brainId: 'b1', token: 'gbt_1.x', baseUrl: 'http://trail.test' } as unknown as BrainLink;
-
-const json = (body: unknown, status = 200) =>
- new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
-
-// --- only to a brain that takes it -------------------------------------------
-
-// An older Trail ignores ?stage=early and would read the partial history as a
-// whole ingest, then refuse the real one as already running. So the flag is
-// read, and absent means no.
-test('a brain that does not say it takes the early upload is not sent one', async () => {
- const older = await fetchExpectedRepo(link, (async () => json({ repo: { slug: 'chalk/chalk', status: 'pending' } })) as typeof fetch);
- assert.equal(older?.earlyUpload, false);
-
- const newer = await fetchExpectedRepo(link, (async () =>
- json({ repo: { slug: 'chalk/chalk', status: 'pending' }, early_upload: true })) as typeof fetch);
- assert.equal(newer?.earlyUpload, true);
-});
-
-test('the early upload is posted with ?stage=early and reports whether Trail took it', async () => {
- let url = '';
- const took = await pushEarlyDigest(link, { owner: 'chalk', name: 'chalk' } as RepoDigest, (async (u: string) => {
- url = u;
- return json({ early: true }, 202);
- }) as typeof fetch);
- assert.equal(took, true);
- assert.match(url, /\/api\/public\/brains\/b1\/repo\?stage=early$/);
-
- const ignored = await pushEarlyDigest(link, {} as RepoDigest, (async () => json({ early: false }, 202)) as typeof fetch);
- assert.equal(ignored, false, 'a brain without the CLAUDE.md step accepts and ignores it');
-
- const refused = await pushEarlyDigest(link, {} as RepoDigest, (async () => json({ error: 'no' }, 409)) as typeof fetch);
- assert.equal(refused, false);
-
- const down = await pushEarlyDigest(link, {} as RepoDigest, (async () => {
- throw new Error('ECONNREFUSED');
- }) as typeof fetch);
- assert.equal(down, false, 'best-effort: the full upload still does everything');
-});
-
-// --- no second read of the same threads --------------------------------------
-
-test('the full read reuses threads the early upload already fetched', async () => {
- const fetched: string[] = [];
- const fake = (async (u: string) => {
- fetched.push(u);
- if (u.includes('/pulls?state=closed')) {
- return json(u.includes('page=1') ? [{ number: 2, title: 'two' }, { number: 1, title: 'one' }] : []);
- }
- return json([{ body: 'use the whole test script', user: { login: 'dev', type: 'User' } }]);
- }) as never;
-
- const early: HistoryThread = { number: 2, title: 'two', body: '', mergeSha: '', comments: [{ body: 'from the early read' }] };
- const threads = await readThreads('chalk', 'chalk', 'tok', fake, 'https://api.test', 200, new Map([[2, early]]));
-
- assert.equal(threads.find((t) => t.number === 2)?.comments[0]?.body, 'from the early read');
- assert.ok(threads.some((t) => t.number === 1), 'the rest is still read');
- assert.ok(!fetched.some((u) => /\/(issues|pulls)\/2\/comments/.test(u)), 'no comment request for #2');
- assert.ok(fetched.some((u) => /\/(issues|pulls)\/1\/comments/.test(u)));
-});
-
-// The early read and the full read share one cache, so a thread the early read
-// is still fetching is waited on, not fetched again — and one with no
-// discussion is remembered too, which a map of finished threads cannot say.
-test('the early and full reads share every GitHub request, even ones in flight', async () => {
- const fetched: string[] = [];
- const fake = (async (u: string) => {
- fetched.push(u);
- await new Promise((r) => setTimeout(r, 5));
- if (u.includes('/pulls?state=closed')) {
- return json(/&page=1$/.test(u) ? Array.from({ length: 40 }, (_, i) => ({ number: 40 - i, title: `pr ${40 - i}` })) : []);
- }
- // Odd pull requests have no discussion at all.
- const n = Number(/\/(\d+)\/comments/.exec(u)?.[1]);
- return json(n % 2 ? [] : [{ body: `on #${n}`, user: { type: 'User' } }]);
- }) as never;
-
- const cache = newThreadReadCache();
- const [early, full] = await Promise.all([
- readThreads('chalk', 'chalk', 'tok', fake, 'https://api.test', 30, undefined, cache),
- readThreads('chalk', 'chalk', 'tok', fake, 'https://api.test', 200, undefined, cache),
- ]);
- assert.equal(early.length, 15);
- assert.equal(full.length, 20);
- const perThread = fetched.filter((u) => /\/issues\/\d+\/comments/.test(u));
- assert.equal(perThread.length, 40, 'each pull request asked about once, however many reads wanted it');
- assert.equal(fetched.filter((u) => u.includes('/pulls?state=closed') && /&page=1$/.test(u)).length, 1, 'the first page of the list is read once');
-});
-
-test('comment reads run in a pool, not in batches that wait for their slowest', async () => {
- let inFlight = 0;
- let peak = 0;
- const fake = (async (u: string) => {
- if (u.includes('/pulls?state=closed')) {
- return json(/&page=1$/.test(u) ? Array.from({ length: 60 }, (_, i) => ({ number: i + 1 })) : []);
- }
- inFlight++;
- peak = Math.max(peak, inFlight);
- await new Promise((r) => setTimeout(r, 2));
- inFlight--;
- return json([]);
- }) as never;
- await readThreads('chalk', 'chalk', 'tok', fake, 'https://api.test', 60);
- assert.equal(peak, THREAD_FETCH_CONCURRENCY * 2, 'two comment endpoints per pull request, 24 pull requests at once');
-});
diff --git a/test/brain-push-agents.test.ts b/test/brain-push-agents.test.ts
deleted file mode 100644
index 1e5593fc..00000000
--- a/test/brain-push-agents.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * The push tells Trail which agents this repo is wired for, so its sidebar
- * shows only the context files those agents read — the same set `graft trail
- * pull` filters by. A repo that has never been wired sends none, and Trail then
- * shows every kind.
- */
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { pickedAgents } from '../src/brain/push.js';
-import { buildDigest } from '../src/app/history.js';
-
-const empty = {
- owner: 'o', name: 'n', headSha: 'h', defaultBranch: 'main', isPrivate: false,
- commits: [], threads: [], symbols: [], sources: [], autoApprove: true,
-};
-
-test('an unwired repo sends no agents', () => {
- const repo = mkdtempSync(join(tmpdir(), 'graft-agents-'));
- assert.deepEqual(pickedAgents(repo), []);
- assert.equal('agents' in buildDigest({ ...empty, agents: pickedAgents(repo) }), false);
-});
-
-test('a repo wired for Claude Code and Cursor sends both', () => {
- const repo = mkdtempSync(join(tmpdir(), 'graft-agents-'));
- mkdirSync(join(repo, '.claude', 'helpers'), { recursive: true });
- writeFileSync(join(repo, '.claude', 'helpers', 'graft-hooks.cjs'), '');
- mkdirSync(join(repo, '.cursor', 'rules'), { recursive: true });
- writeFileSync(join(repo, '.cursor', 'rules', 'graft.mdc'), '---\n---\n');
- const agents = pickedAgents(repo);
- assert.ok(agents.includes('claude'));
- assert.ok(agents.includes('cursor'));
- assert.deepEqual(buildDigest({ ...empty, agents }).agents, agents);
-});
diff --git a/test/brain-signup.test.ts b/test/brain-signup.test.ts
deleted file mode 100644
index 098be1d1..00000000
--- a/test/brain-signup.test.ts
+++ /dev/null
@@ -1,218 +0,0 @@
-/**
- * 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 { mkdtempSync, readFileSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { CALLBACK_PATH, claimSignup, newSignupState, signupUrl, startHandoff, waitForSignup } from "../src/brain/signup.js";
-import { clearPendingSignup, readPendingSignup, writePendingSignup } from "../src/brain/link.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, /no sign-up after .* · nothing was sent — run graft trail push again/);
-});
-
-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" }));
- // Trail's front end, not the shared agents host link.ts calls for the API:
- // the signup a person walks through has to be the Trail-branded build.
- assert.equal(url.origin, "https://app.trailhq.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;
- }
-});
-
-// The browser's last stop is Trail, not a local page that is about to stop
-// answering. Ending on "go back to your terminal" wasted the one moment the
-// brain is actually being built and there is something on screen worth seeing.
-//
-// And specifically the BUILD screen, not `/brain/<id>`, which is where this went
-// first: that route redirects to the brain's graph the instant the row exists,
-// which is minutes before it holds a single rule. So every terminal signup was
-// landing on an empty visualisation of a brain that was building perfectly well.
-test('the accepted handoff sends the browser to the build screen, not an empty graph', async () => {
- process.env.GRAFT_BRAIN_URL = 'http://localhost:5173';
- const handoff = await startHandoff();
- try {
- const res = await fetch(
- `http://127.0.0.1:${handoff.port}${CALLBACK_PATH}?state=${encodeURIComponent(handoff.state)}&brain=abc-123&token=gbt_1.xyz`,
- { redirect: 'manual' },
- );
- assert.equal(res.status, 303);
- assert.equal(res.headers.get('location'), 'http://localhost:5173/get-started?step=build&brain=abc-123');
- const got = await handoff.wait(1000);
- assert.deepEqual(got, { link: { brainId: 'abc-123', token: 'gbt_1.xyz' } });
- } finally {
- handoff.close();
- delete process.env.GRAFT_BRAIN_URL;
- }
-});
-
-// --- signing up when an agent runs the push ---
-
-/** A fetch that answers each call with the next status in `script`. */
-function scripted(script: Array<{ status: number; body?: unknown }>) {
- const calls: Array<{ url: string; body: string }> = [];
- const impl = (async (url: string | URL | Request, init?: RequestInit) => {
- calls.push({ url: String(url), body: String(init?.body ?? "") });
- const next = script[Math.min(calls.length - 1, script.length - 1)];
- return new Response(next.body === undefined ? null : JSON.stringify(next.body), { status: next.status });
- }) as typeof fetch;
- return { impl, calls };
-}
-
-test("agent signup: the link carries no port, because nothing is listening", () => {
- const url = new URL(signupUrl({ repo: "acme/app", state: "st", baseUrl: "https://trail.example" }));
- assert.equal(url.searchParams.get("graft_port"), null);
- assert.equal(url.searchParams.get("graft_repo"), "acme/app");
- assert.equal(url.searchParams.get("graft_state"), "st");
-});
-
-test("trail links go to the pages host when it differs from the API, and say they're trail's", () => {
- const prev = { web: process.env.TRAIL_WEB_URL, api: process.env.GRAFT_BRAIN_URL, brand: process.env.TRAIL_INVOKED_AS };
- process.env.TRAIL_WEB_URL = "http://localhost:5176/";
- process.env.GRAFT_BRAIN_URL = "http://localhost:8095";
- process.env.TRAIL_INVOKED_AS = "trail";
- try {
- const url = new URL(signupUrl({ repo: "acme/app", state: "st" }));
- assert.equal(url.origin, "http://localhost:5176");
- assert.equal(url.searchParams.get("graft_mode"), "trail");
- } finally {
- for (const [k, v] of [["TRAIL_WEB_URL", prev.web], ["GRAFT_BRAIN_URL", prev.api], ["TRAIL_INVOKED_AS", prev.brand]] as const) {
- if (v === undefined) delete process.env[k];
- else process.env[k] = v;
- }
- }
-});
-
-test("agent signup: a fresh state is long enough for Trail to accept", () => {
- // Trail refuses anything under 32 characters of base64url.
- assert.match(newSignupState(), /^[A-Za-z0-9_-]{32,128}$/);
-});
-
-test("agent signup: the state goes in the body, not the URL", async () => {
- const f = scripted([{ status: 202, body: { status: "pending" } }]);
- const got = await claimSignup("secret-state", "https://api.example", f.impl);
- assert.deepEqual(got, { pending: true });
- assert.equal(f.calls[0].url, "https://api.example/api/public/graft-handoffs/claim");
- assert.ok(!f.calls[0].url.includes("secret-state"));
- assert.deepEqual(JSON.parse(f.calls[0].body), { state: "secret-state" });
-});
-
-test("agent signup: keeps asking until the sign-up finishes, then hands back the link", async () => {
- const f = scripted([
- { status: 202, body: { status: "pending" } },
- { status: 503 },
- { status: 200, body: { brain_id: "brain-1", token: "gbt_1.sig" } },
- ]);
- const got = await waitForSignup("st", "https://api.example", { timeoutMs: 5000, intervalMs: 1, fetchImpl: f.impl });
- assert.deepEqual(got, { link: { brainId: "brain-1", token: "gbt_1.sig" } });
- assert.equal(f.calls.length, 3, "a server error in the middle is not a reason to stop");
-});
-
-test("agent signup: stops at once on a used or expired link", async () => {
- const f = scripted([{ status: 410, body: { error: "gone" } }]);
- const got = await waitForSignup("st", "https://api.example", { timeoutMs: 5000, intervalMs: 1, fetchImpl: f.impl });
- assert.ok("error" in got && got.reason === "expired");
- assert.equal(f.calls.length, 1);
-});
-
-test("agent signup: an older Trail without the route is unsupported, not an endless wait", async () => {
- const f = scripted([{ status: 404 }]);
- const got = await waitForSignup("st", "https://api.example", { timeoutMs: 5000, intervalMs: 1, fetchImpl: f.impl });
- assert.ok("error" in got && got.reason === "unsupported");
-});
-
-test("agent signup: gives up as still pending when the wait runs out", async () => {
- const f = scripted([{ status: 202, body: { status: "pending" } }]);
- const got = await waitForSignup("st", "https://api.example", { timeoutMs: 30, intervalMs: 10, fetchImpl: f.impl });
- assert.deepEqual(got, { pending: true });
-});
-
-test("agent signup: the saved state is for one repo, for a while, and git-ignored", () => {
- const dir = mkdtempSync(join(tmpdir(), "graft-pending-"));
- try {
- writePendingSignup(dir, { state: "st", repo: "acme/app", createdAt: 1_000 });
- assert.equal(readPendingSignup(dir, "acme/app", 60_000, 2_000)?.state, "st");
- assert.equal(readPendingSignup(dir, "acme/other", 60_000, 2_000), null, "a different remote starts over");
- assert.equal(readPendingSignup(dir, "acme/app", 60_000, 70_000), null, "too old to claim");
- assert.match(readFileSync(join(dir, ".gitignore"), "utf8"), /\.graft/);
- clearPendingSignup(dir);
- assert.equal(readPendingSignup(dir, "acme/app", 60_000, 2_000), null);
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
-});
diff --git a/test/brain-trail-watch.test.ts b/test/brain-trail-watch.test.ts
deleted file mode 100644
index 84d41743..00000000
--- a/test/brain-trail-watch.test.ts
+++ /dev/null
@@ -1,232 +0,0 @@
-/**
- * `graft trail watch` replaces a polling loop agents used to write for
- * themselves, so what matters is when it stops and what it says when it does:
- * suggestions with nothing accepted stop it at once, accepted changes stop it
- * only once they hold still, a timeout is its own exit code, and a failed read
- * is retried rather than reported. Trail is faked at the fetch layer, as in the
- * pull tests, and the clock is faked so an hour's watch takes no time.
- */
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import { mkdirSync, writeFileSync } from 'node:fs';
-import { dirname, join } from 'node:path';
-import {
- filesSummary,
- readTrailSnapshot,
- watchExitCode,
- watchExitJson,
- watchExitLines,
- watchTrail,
- type WatchTrailOptions,
- withWatchHeader,
-} from '../src/brain/watch-trail.js';
-import type { BrainLink } from '../src/brain/link.js';
-import { runCli, tmpRepo } from './helpers.js';
-
-const link = { brainId: 'b1', token: 'gbt_1.x', baseUrl: 'http://trail.test' } as unknown as BrainLink;
-const json = (body: unknown, status = 200) =>
- new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
-
-function put(root: string, rel: string, text: string): void {
- mkdirSync(dirname(join(root, rel)), { recursive: true });
- writeFileSync(join(root, rel), text);
-}
-
-/** What Trail holds on one read. */
-interface TrailView {
- /** CLAUDE.md suggestions Trail has made (the counts on GET /repo). */
- suggested?: number;
- claudeMd?: unknown[];
- files?: unknown[];
- /** Make this read fail: a thrown fetch (the network), or a status. */
- fail?: 'network' | number;
-}
-
-/** A Trail that answers each read from the next view in `views`, holding the last. */
-function fakeTrail(views: TrailView[]) {
- let read = 0;
- let current: TrailView = views[0]!;
- const f = (async (u: string) => {
- const path = new URL(u).pathname;
- // Each read asks for /repo, /claude-md and /context-files, in that order
- // and all at once; the first of them is what moves to the next view.
- if (path.endsWith('/repo')) current = views[Math.min(read++, views.length - 1)]!;
- if (current.fail === 'network') throw new TypeError('fetch failed');
- if (typeof current.fail === 'number') return json({ error: 'no' }, current.fail);
- if (path.endsWith('/claude-md')) return json({ path: 'CLAUDE.md', head_sha: 'abc', changes: current.claudeMd ?? [] });
- if (path.endsWith('/context-files')) return json({ head_sha: 'abc', files: current.files ?? [] });
- if (path.endsWith('/repo')) {
- return json({ repo: { status: 'completed', rule_count: 10 }, claude_md: { status: 'ready', changes: current.suggested ?? 0 } });
- }
- return json({ error: 'unexpected' }, 500);
- }) as typeof fetch;
- return { f, reads: () => read };
-}
-
-/** A clock that only moves when the watch sleeps. */
-function fakeClock() {
- let t = 1_000_000;
- return { now: () => t, sleep: async (ms: number) => void (t += ms), elapsed: () => t - 1_000_000 };
-}
-
-const COMMANDS = { id: 'm1', kind: 'edit', heading: 'Commands', find: '', text: '- `npm run lint`' };
-const TESTING = { id: 'm2', kind: 'add', heading: 'Testing', after_heading: 'Commands', text: 'node:test.' };
-const SEO = { kind: 'folder_claude_md', path: 'web/CLAUDE.md', changes: [{ id: 'w1', kind: 'edit', heading: 'SEO metadata', find: '', text: 'Every page sets a title.' }] };
-
-function repoWithClaudeMd(tag: string): string {
- const root = tmpRepo(tag);
- put(root, 'CLAUDE.md', '# app\n\n## Commands\n\n- `npm test`\n');
- return root;
-}
-
-function opts(f: typeof fetch, clock: ReturnType<typeof fakeClock>, extra: Partial<WatchTrailOptions> = {}): WatchTrailOptions {
- return { wired: ['claude'], fetchImpl: f, now: clock.now, sleep: clock.sleep, ...extra };
-}
-
-test('suggestions with nothing accepted end the watch on the first read', async () => {
- const root = repoWithClaudeMd('watch-suggested');
- const { f, reads } = fakeTrail([{ suggested: 5 }]);
- const clock = fakeClock();
- const r = await watchTrail(root, link, opts(f, clock));
- assert.equal(r.reason, 'suggestions');
- assert.equal(reads(), 1);
- assert.equal(watchExitCode(r), 0);
- const lines = watchExitLines(r, 3_600_000);
- assert.equal(lines.length, 2);
- assert.equal(lines[0], '● 5 suggestions are waiting for review');
- assert.equal(lines[1], ` review: ${r.reviewUrl}`);
- assert.match(r.reviewUrl, /\/brain\/b1\/context-files$/);
-});
-
-test('--accepted-only waits through suggestions, then times out with exit code 2', async () => {
- const root = repoWithClaudeMd('watch-accepted-only');
- const { f, reads } = fakeTrail([{ suggested: 5 }]);
- const clock = fakeClock();
- const r = await watchTrail(root, link, opts(f, clock, { acceptedOnly: true, intervalMs: 60_000, timeoutMs: 60 * 60_000 }));
- assert.equal(r.reason, 'timeout');
- assert.equal(watchExitCode(r), 2);
- assert.equal(clock.elapsed(), 60 * 60_000, 'the last read is at the deadline, not past it');
- assert.equal(reads(), 61, 'one read a minute, plus the one at the start');
- const lines = watchExitLines(r, 60 * 60_000);
- assert.equal(lines[0], '· still waiting after 60 minutes: 5 suggested, 0 accepted');
- assert.match(lines[1]!, /^ {2}review: \S+\/brain\/b1\/context-files$/);
-});
-
-test('accepted changes are reported only once they have held still for --settle', async () => {
- const root = repoWithClaudeMd('watch-accepted');
- const { f, reads } = fakeTrail([{ suggested: 9, claudeMd: [COMMANDS, TESTING], files: [SEO] }]);
- const clock = fakeClock();
- const r = await watchTrail(root, link, opts(f, clock, { settleMs: 60_000, intervalMs: 60_000 }));
- assert.equal(r.reason, 'accepted');
- assert.equal(reads(), 2, 'not on the first read, which may be someone mid-review');
- assert.equal(r.accepted, 3);
- assert.equal(watchExitCode(r), 0);
- assert.deepEqual(watchExitLines(r, 3_600_000), [
- '✓ 3 accepted changes are ready: CLAUDE.md (Commands, Testing), web/CLAUDE.md (SEO metadata)',
- ' run graft trail pull to write them',
- ]);
-});
-
-test('a change to the accepted set starts the settle over', async () => {
- const root = repoWithClaudeMd('watch-resettle');
- const { f, reads } = fakeTrail([
- { claudeMd: [COMMANDS] },
- { claudeMd: [COMMANDS, TESTING] },
- { claudeMd: [TESTING] }, // same count as the first read, different change
- { claudeMd: [TESTING] },
- ]);
- const clock = fakeClock();
- const r = await watchTrail(root, link, opts(f, clock, { settleMs: 60_000, intervalMs: 60_000 }));
- assert.equal(r.reason, 'accepted');
- assert.equal(reads(), 4);
- assert.deepEqual(watchExitLines(r, 3_600_000), ['✓ 1 accepted change is ready: CLAUDE.md (Testing)', ' run graft trail pull to write it']);
-});
-
-test('changes already in the files are not waiting for anything', async () => {
- const root = tmpRepo('watch-present');
- put(root, 'CLAUDE.md', '# app\n\n## Testing\n\nnode:test.\n');
- const snap = await readTrailSnapshot(root, link, ['claude'], fakeTrail([{ suggested: 1, claudeMd: [{ ...TESTING, after_heading: '' }] }]).f);
- assert.ok(snap.ok);
- assert.equal(snap.snapshot.accepted, 0);
- assert.equal(snap.snapshot.suggested, 1);
-});
-
-test('a failed read is retried on the next tick instead of ending the watch', async () => {
- const root = repoWithClaudeMd('watch-retry');
- const { f, reads } = fakeTrail([{ fail: 'network' }, { fail: 502 }, { suggested: 2 }]);
- const clock = fakeClock();
- const ticks: boolean[] = [];
- const r = await watchTrail(root, link, opts(f, clock, { onTick: (t) => ticks.push(t.ok) }));
- assert.equal(r.reason, 'suggestions');
- assert.equal(reads(), 3);
- assert.deepEqual(ticks, [false, false, true]);
- assert.deepEqual(watchExitLines(r, 3_600_000)[0], '● 2 suggestions are waiting for review');
-});
-
-test('a token Trail refuses ends the watch at once, with exit code 1', async () => {
- const root = repoWithClaudeMd('watch-refused');
- const { f, reads } = fakeTrail([{ fail: 401 }]);
- const r = await watchTrail(root, link, opts(f, fakeClock()));
- assert.equal(r.reason, 'refused');
- assert.equal(reads(), 1);
- assert.equal(watchExitCode(r), 1);
- assert.match(watchExitLines(r, 3_600_000).join('\n'), /✗ Trail refused the pull: 401[\s\S]*graft trail connect/);
-});
-
-test('a Trail never reached times out saying so', async () => {
- const root = repoWithClaudeMd('watch-unreachable');
- const { f } = fakeTrail([{ fail: 'network' }]);
- const r = await watchTrail(root, link, opts(f, fakeClock(), { timeoutMs: 5 * 60_000 }));
- assert.equal(r.reason, 'timeout');
- assert.equal(watchExitCode(r), 2);
- assert.deepEqual(watchExitLines(r, 5 * 60_000), ['· still waiting after 5 minutes: could not reach Trail']);
-});
-
-test('--json carries the same ending', async () => {
- const root = repoWithClaudeMd('watch-json');
- const { f } = fakeTrail([{ suggested: 4, claudeMd: [COMMANDS] }]);
- const clock = fakeClock();
- const r = await watchTrail(root, link, opts(f, clock, { settleMs: 0 }));
- assert.deepEqual(watchExitJson(r), {
- reason: 'accepted',
- suggested: 4,
- accepted: 1,
- files: [{ path: 'CLAUDE.md', headings: ['Commands'] }],
- review_url: r.reviewUrl,
- waited_s: 0,
- });
-});
-
-test('a whole-file change names its file and no section', () => {
- assert.equal(filesSummary([{ path: '.cursor/rules/money.mdc', headings: [] }, { path: 'CLAUDE.md', headings: ['Money'] }]), '.cursor/rules/money.mdc, CLAUDE.md (Money)');
-});
-
-test('graft trail watch on a repo with no trail exits 1 at once, and --help documents it', () => {
- const root = tmpRepo('watch-cli-unlinked');
- const run = runCli(['trail', 'watch', root, '--json'], { home: root });
- assert.equal(run.status, 1, run.describe());
- assert.equal(JSON.parse(run.stdout).reason, 'no_trail');
-
- const help = runCli(['trail', 'watch', '--help'], { home: root });
- assert.equal(help.status, 0, help.describe());
- assert.match(help.stdout, /Wait until Trail has suggestions to review or accepted changes to pull/);
- assert.match(help.stdout, /--accepted-only/);
- assert.match(help.stdout, /exit 2/);
-});
-
-// Trail tells the page that Claude Code is watching from this header; a watch
-// must send it on every read, and a manual pull must not (it uses gatherPull
-// with a plain fetch).
-test('withWatchHeader adds X-Graft-Watch to every request and keeps the rest', async () => {
- const seen: Headers[] = [];
- const inner = (async (_u: string, init?: RequestInit) => {
- seen.push(new Headers(init?.headers));
- return new Response('{}', { status: 200 });
- }) as unknown as typeof fetch;
- const f = withWatchHeader(inner);
- await f('http://trail.test/a', { headers: { authorization: 'Bearer t', accept: 'application/json' } });
- await f('http://trail.test/b');
- assert.equal(seen[0]!.get('x-graft-watch'), '1');
- assert.equal(seen[0]!.get('authorization'), 'Bearer t');
- assert.equal(seen[1]!.get('x-graft-watch'), '1');
-});
diff --git a/test/brain-upload.test.ts b/test/brain-upload.test.ts
deleted file mode 100644
index 6daf4520..00000000
--- a/test/brain-upload.test.ts
+++ /dev/null
@@ -1,243 +0,0 @@
-/**
- * The full digest goes up gzipped, and in retried 1 MiB chunks when Trail says
- * it takes them. What matters: the chunks reassemble into exactly the gzip of
- * the body a single POST would have sent, a blip costs one chunk rather than
- * the push, and an older Trail still gets the plain POST it always did.
- */
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import { gunzipSync } from 'node:zlib';
-import { uploadDigest, uploadChunked, RETRY_DELAYS_MS } from '../src/brain/upload.js';
-import { fetchExpectedRepo, pushEarlyDigest, uploadCaps } from '../src/brain/push.js';
-import type { RepoDigest } from '../src/app/history.js';
-import type { BrainLink } from '../src/brain/link.js';
-
-const link = { brainId: 'b1', token: 'gbt_1.x', baseUrl: 'http://trail.test' } as unknown as BrainLink;
-const json = (body: unknown, status = 200) =>
- new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
-
-/** A digest big enough to need several chunks at a small chunk size. */
-function digest(): RepoDigest {
- return {
- provider: 'github',
- owner: 'chalk',
- name: 'chalk',
- head_sha: 'abc',
- default_branch: 'main',
- is_private: false,
- commits: Array.from({ length: 400 }, (_, i) => ({
- sha: `${i}`.padStart(40, '0'),
- subject: `commit ${i} ${Math.random().toString(36)}`,
- body: '',
- files: [`src/${i}.ts`],
- symbols: [],
- })),
- threads: [],
- symbols: [],
- sources: [],
- auto_approve: true,
- };
-}
-
-interface Call {
- method: string;
- url: string;
- headers: Record<string, string>;
- body: unknown;
-}
-
-function recorder(respond: (c: Call, n: number) => Response | Promise<Response>) {
- const calls: Call[] = [];
- const f = (async (u: string, init?: RequestInit) => {
- const c: Call = {
- method: init?.method ?? 'GET',
- url: u,
- headers: (init?.headers ?? {}) as Record<string, string>,
- body: init?.body,
- };
- calls.push(c);
- return respond(c, calls.length);
- }) as typeof fetch;
- return { calls, f };
-}
-
-const noSleep = { sleep: async () => {} };
-
-test('chunks reassemble into the gzip of exactly the body a single POST would send', async () => {
- const d = digest();
- const chunks = new Map<number, Buffer>();
- let opened: Record<string, unknown> = {};
- const { calls, f } = recorder((c) => {
- if (c.method === 'POST' && c.url.endsWith('/repo/uploads')) {
- opened = JSON.parse(String(c.body));
- return json({ upload_id: 'u-1' }, 201);
- }
- const m = /\/uploads\/u-1\/chunks\/(\d+)$/.exec(c.url);
- if (c.method === 'PUT' && m) {
- chunks.set(Number(m[1]), Buffer.from(c.body as Uint8Array));
- return new Response(null, { status: 204 });
- }
- if (c.url.endsWith('/uploads/u-1/complete')) return json({ repo: {}, job_id: 'job-9', status: 'queued' }, 202);
- return json({ error: 'unexpected' }, 500);
- });
-
- const got = await uploadDigest(link, d, { gzip: true, chunked: true }, { fetchImpl: f, chunkBytes: 2048, ...noSleep });
- assert.deepEqual(got, { jobId: 'job-9' });
-
- assert.equal(opened.stage, 'full');
- assert.equal(opened.auto_approve, true);
- assert.equal(opened.chunks, chunks.size);
- assert.ok(chunks.size > 1, 'the test digest must need more than one chunk');
- const joined = Buffer.concat([...chunks.keys()].sort((a, b) => a - b).map((i) => chunks.get(i)!));
- assert.equal(opened.bytes, joined.length);
- assert.equal(gunzipSync(joined).toString('utf8'), JSON.stringify(d));
-
- const put = calls.find((c) => c.method === 'PUT')!;
- assert.equal(put.headers['content-type'], 'application/octet-stream');
- assert.equal(put.headers.authorization, 'Bearer gbt_1.x');
- assert.match(put.url, /^http:\/\/trail\.test\/api\/public\/brains\/b1\/repo\/uploads\/u-1\/chunks\/\d+$/);
-});
-
-test('a chunk that fails is retried on its own, on 5xx, 429 and network errors', async () => {
- const attempts = new Map<string, number>();
- const waits: number[] = [];
- const { f } = recorder((c) => {
- if (c.url.endsWith('/repo/uploads')) return json({ upload_id: 'u-2' }, 201);
- if (c.method === 'PUT') {
- const n = (attempts.get(c.url) ?? 0) + 1;
- attempts.set(c.url, n);
- if (c.url.endsWith('/chunks/1')) {
- if (n === 1) return json({ error: 'busy' }, 503);
- if (n === 2) return json({ error: 'slow down' }, 429);
- if (n === 3) throw new Error('ECONNRESET');
- }
- return new Response(null, { status: 204 });
- }
- return json({ job_id: 'job-2' }, 202);
- });
- const got = await uploadChunked(link, digest(), {
- fetchImpl: f,
- chunkBytes: 2048,
- sleep: async (ms) => void waits.push(ms),
- });
- assert.deepEqual(got, { jobId: 'job-2' });
- assert.equal(attempts.get('http://trail.test/api/public/brains/b1/repo/uploads/u-2/chunks/1'), 4);
- assert.equal(attempts.get('http://trail.test/api/public/brains/b1/repo/uploads/u-2/chunks/0'), 1, 'the others went once');
- assert.deepEqual(waits, [500, 1000, 2000], 'backoff doubles from half a second');
-});
-
-test('a chunk that keeps failing gives up after four retries and says which part', async () => {
- let tries = 0;
- const { f } = recorder((c) => {
- if (c.url.endsWith('/repo/uploads')) return json({ upload_id: 'u-3' }, 201);
- if (c.method === 'PUT') {
- tries++;
- return json({ error: 'down' }, 502);
- }
- return json({ job_id: 'never' }, 202);
- });
- const got = await uploadChunked(link, digest(), { fetchImpl: f, chunkBytes: 1 << 20, ...noSleep });
- assert.ok('error' in got && /part 1 of 1: 502/.test(got.error), JSON.stringify(got));
- assert.equal(tries, RETRY_DELAYS_MS.length + 1);
-});
-
-test('complete is retried on 5xx, and returns today\'s ingest response', async () => {
- let completes = 0;
- const { f } = recorder((c) => {
- if (c.url.endsWith('/repo/uploads')) return json({ upload_id: 'u-4' }, 201);
- if (c.method === 'PUT') return new Response(null, { status: 204 });
- completes++;
- return completes < 3 ? json({ error: 'hiccup' }, 500) : json({ repo: {}, job_id: 'job-4', status: 'queued' }, 202);
- });
- assert.deepEqual(await uploadChunked(link, digest(), { fetchImpl: f, ...noSleep }), { jobId: 'job-4' });
- assert.equal(completes, 3);
-});
-
-test('a 409 from complete is passed on as a refusal, as the single POST would be', async () => {
- const { f } = recorder((c) => {
- if (c.url.endsWith('/repo/uploads')) return json({ upload_id: 'u-5' }, 201);
- if (c.method === 'PUT') return new Response(null, { status: 204 });
- return json({ error: 'an ingest is already running' }, 409);
- });
- const got = await uploadChunked(link, digest(), { fetchImpl: f, ...noSleep });
- assert.ok('error' in got && /409 .*already running/.test(got.error));
-});
-
-test('a complete lost on the way back, then told 409 on its retry, counts as started', async () => {
- let completes = 0;
- const { f } = recorder((c) => {
- if (c.url.endsWith('/repo/uploads')) return json({ upload_id: 'u-6' }, 201);
- if (c.method === 'PUT') return new Response(null, { status: 204 });
- completes++;
- if (completes === 1) throw new Error('socket hang up');
- return json({ error: 'an ingest is already running' }, 409);
- });
- assert.deepEqual(await uploadChunked(link, digest(), { fetchImpl: f, ...noSleep }), { jobId: '' });
-});
-
-test('a server that advertised chunks but has no route falls back to the single POST', async () => {
- const { calls, f } = recorder((c) => {
- if (c.url.endsWith('/repo/uploads')) return json({ error: 'not found' }, 404);
- return json({ job_id: 'job-7' }, 202);
- });
- const got = await uploadDigest(link, digest(), { chunked: true, gzip: true }, { fetchImpl: f, ...noSleep });
- assert.deepEqual(got, { jobId: 'job-7' });
- const post = calls.at(-1)!;
- assert.equal(post.url, 'http://trail.test/api/public/brains/b1/repo');
- assert.equal(post.headers['content-encoding'], 'gzip');
-});
-
-test('an older Trail gets the plain POST it always did', async () => {
- const d = digest();
- const { calls, f } = recorder(() => json({ job_id: 'job-8' }, 202));
- assert.deepEqual(await uploadDigest(link, d, {}, { fetchImpl: f }), { jobId: 'job-8' });
- assert.equal(calls.length, 1);
- assert.equal(calls[0].headers['content-encoding'], undefined);
- assert.equal(calls[0].body, JSON.stringify(d));
-});
-
-test('gzip alone is one gzipped POST of the same body', async () => {
- const d = digest();
- const { calls, f } = recorder(() => json({ job_id: 'job-10' }, 202));
- await uploadDigest(link, d, { gzip: true }, { fetchImpl: f });
- assert.equal(calls.length, 1);
- assert.equal(calls[0].headers['content-encoding'], 'gzip');
- assert.equal(gunzipSync(Buffer.from(calls[0].body as Uint8Array)).toString('utf8'), JSON.stringify(d));
-});
-
-test('the early upload is gzipped only when Trail says it takes gzip', async () => {
- const { calls, f } = recorder(() => json({ early: true }, 202));
- assert.equal(await pushEarlyDigest(link, digest(), f, { gzip: true }), true);
- assert.equal(calls[0].headers['content-encoding'], 'gzip');
- assert.match(calls[0].url, /\/repo\?stage=early$/);
- await pushEarlyDigest(link, digest(), f);
- assert.equal(calls[1].headers['content-encoding'], undefined);
-});
-
-test('the capability flags are read off the expected-repo response, and default to off', async () => {
- const older = await fetchExpectedRepo(link, (async () => json({ repo: { slug: 'chalk/chalk' } })) as typeof fetch);
- assert.deepEqual(uploadCaps(older), { gzip: false, chunked: false });
- assert.equal(older?.events, false);
- const newer = await fetchExpectedRepo(link, (async () =>
- json({ repo: { slug: 'chalk/chalk', rule_count: 12 }, gzip_upload: true, chunked_upload: true, events: true })) as typeof fetch);
- assert.deepEqual(uploadCaps(newer), { gzip: true, chunked: true });
- assert.equal(newer?.events, true);
- assert.equal(newer?.ruleCount, 12);
-});
-
-test('every call honours GRAFT_BRAIN_URL', async () => {
- const before = process.env.GRAFT_BRAIN_URL;
- process.env.GRAFT_BRAIN_URL = 'https://staging-agents.test/';
- try {
- const { calls, f } = recorder((c) => {
- if (c.url.endsWith('/repo/uploads')) return json({ upload_id: 'u-9' }, 201);
- if (c.method === 'PUT') return new Response(null, { status: 204 });
- return json({ job_id: 'j' }, 202);
- });
- await uploadChunked(link, digest(), { fetchImpl: f, ...noSleep });
- for (const c of calls) assert.ok(c.url.startsWith('https://staging-agents.test/api/public/brains/b1/repo/uploads'), c.url);
- } finally {
- if (before === undefined) delete process.env.GRAFT_BRAIN_URL;
- else process.env.GRAFT_BRAIN_URL = before;
- }
-});
diff --git a/test/brain-watch-events.test.ts b/test/brain-watch-events.test.ts
deleted file mode 100644
index c14e223b..00000000
--- a/test/brain-watch-events.test.ts
+++ /dev/null
@@ -1,198 +0,0 @@
-/**
- * The live watch: when Trail streams the build, the terminal follows it as it
- * happens instead of polling every four seconds. What matters is that the
- * stream is parsed exactly (keep-alives, split chunks, CRLF), that the suggestion
- * counts ride along, and that a stream which drops costs nothing but the old
- * polling behaviour.
- */
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import { parseRepoBody, SseParser, watchBuild } from '../src/brain/watch.js';
-
-const LINK = { brainId: 'b1', token: 'gbt_1.sig', baseUrl: 'http://trail.test' };
-
-// --- the parser ---------------------------------------------------------------
-
-test('events are parsed across chunk boundaries, and keep-alives are dropped', () => {
- const p = new SseParser();
- assert.deepEqual(p.push(': ping\n\nevent: prog'), []);
- assert.deepEqual(p.push('ress\ndata: {"a":'), []);
- assert.deepEqual(p.push('1}\n\n'), [{ event: 'progress', data: '{"a":1}' }]);
- assert.deepEqual(p.push('event: done\r\ndata: {}\r\n\r\n'), [{ event: 'done', data: '{}' }]);
-});
-
-test('multi-line data is joined, and a missing event name means message', () => {
- const p = new SseParser();
- assert.deepEqual(p.push('data: one\ndata:two\n\n'), [{ event: 'message', data: 'one\ntwo' }]);
-});
-
-test('a lone CR at the end of a chunk waits for its LF', () => {
- const p = new SseParser();
- assert.deepEqual(p.push('data: x\r'), []);
- assert.deepEqual(p.push('\n\r\n'), [{ event: 'message', data: 'x' }]);
-});
-
-test('the suggestion counts are read whether Trail sends numbers or lists', () => {
- const counted = parseRepoBody({
- repo: { status: 'ingesting' },
- claude_md: { status: 'ready', quick_ready: true, changes: 3 },
- context_files: { files: 2, changes: 5 },
- });
- assert.deepEqual(counted?.suggestions, { claudeMd: 3, contextFiles: 5 });
- const listed = parseRepoBody({
- repo: { status: 'ingesting' },
- claude_md: { changes: [{}, {}] },
- context_files: { files: [{ kind: 'agents_md', path: 'AGENTS.md', changes: [{}, {}, {}] }] },
- });
- assert.deepEqual(listed?.suggestions, {
- claudeMd: 2,
- contextFiles: 3,
- files: [{ kind: 'agents_md', path: 'AGENTS.md', changes: 3 }],
- });
- assert.equal(parseRepoBody({ repo: { status: 'ingesting' } })?.suggestions, undefined, 'an older Trail sends none');
-});
-
-test('the polled GET carries the context-file counts in context_files_progress', () => {
- // On GET /repo, `context_files` is the flag that says the routes exist.
- const polled = parseRepoBody({
- repo: { status: 'completed' },
- claude_md: { status: 'analyzing', changes: 3 },
- context_files: true,
- context_files_progress: { changes: 2, files: [{ kind: 'skill', path: '.claude/skills/a/SKILL.md', changes: 2 }] },
- });
- assert.deepEqual(polled?.suggestions, {
- claudeMd: 3,
- contextFiles: 2,
- files: [{ kind: 'skill', path: '.claude/skills/a/SKILL.md', changes: 2 }],
- });
-});
-
-// --- the stream ---------------------------------------------------------------
-
-/** A text/event-stream response that sends each part in turn, then ends (or not). */
-function stream(parts: string[], opts: { end?: boolean } = {}): Response {
- const enc = new TextEncoder();
- let i = 0;
- const body = new ReadableStream<Uint8Array>({
- pull(ctl) {
- if (i < parts.length) ctl.enqueue(enc.encode(parts[i++]));
- else if (opts.end !== false) ctl.close();
- },
- });
- return new Response(body, { status: 200, headers: { 'content-type': 'text/event-stream' } });
-}
-
-const progress = (body: unknown) => `event: progress\ndata: ${JSON.stringify(body)}\n\n`;
-const NOW = { timeoutMs: 60_000, pollMs: 0, sleep: async () => {} };
-
-test('the stream settles the watch on the first rules, with the suggestions it carried', async () => {
- const urls: string[] = [];
- const accepts: string[] = [];
- let seen: unknown = null;
- const outcome = await watchBuild(LINK, {
- ...NOW,
- events: true,
- write: () => {},
- onState: (_v, repo) => (seen = repo.suggestions),
- fetchImpl: (async (u: string, init?: RequestInit) => {
- urls.push(u);
- accepts.push(String((init?.headers as Record<string, string>).accept));
- return stream([
- ': ping\n\n',
- progress({ repo: { status: 'ingesting', commit_count: 412 } }),
- progress({
- repo: { status: 'ingesting', commit_count: 412 },
- build: { found_so_far: 40, filed_so_far: 5 },
- claude_md: { changes: 4 },
- context_files: { changes: 2 },
- }),
- ], { end: false });
- }) as typeof fetch,
- });
- assert.equal(outcome, 'building');
- assert.deepEqual(urls, ['http://trail.test/api/public/brains/b1/events'], 'one connection, no polling');
- assert.equal(accepts[0], 'text/event-stream');
- assert.deepEqual(seen, { claudeMd: 4, contextFiles: 2 });
-});
-
-test('a done event reports a failed build the same way polling would', async () => {
- const lines: string[] = [];
- const outcome = await watchBuild(LINK, {
- ...NOW,
- events: true,
- write: (l) => lines.push(l),
- fetchImpl: (async () =>
- stream([
- progress({ repo: { status: 'ingesting', commit_count: 10 } }),
- `event: done\ndata: ${JSON.stringify({ repo: { status: 'failed', commit_count: 10, error_message: 'miner fell over' } })}\n\n`,
- ])) as typeof fetch,
- });
- assert.equal(outcome, 'failed');
- assert.match(lines.join('\n'), /the build stopped while mining rules · nothing was lost/);
- assert.match(lines.join('\n'), /miner fell over/);
-});
-
-test('a stream that keeps dropping is reopened three times, then the watcher polls', async () => {
- const hits: string[] = [];
- const outcome = await watchBuild(LINK, {
- ...NOW,
- events: true,
- write: () => {},
- fetchImpl: (async (u: string) => {
- hits.push(u.endsWith('/events') ? 'events' : 'poll');
- if (u.endsWith('/events')) return stream([progress({ repo: { status: 'ingesting' } })]);
- return new Response(JSON.stringify({ repo: { status: 'completed', rule_count: 42, commit_count: 9 } }), { status: 200 });
- }) as typeof fetch,
- });
- assert.equal(outcome, 'completed');
- assert.deepEqual(hits, ['events', 'events', 'events', 'events', 'poll']);
-});
-
-test('a Trail without the stream falls straight back to polling', async () => {
- const hits: string[] = [];
- const outcome = await watchBuild(LINK, {
- ...NOW,
- events: true,
- write: () => {},
- fetchImpl: (async (u: string) => {
- hits.push(u.endsWith('/events') ? 'events' : 'poll');
- if (u.endsWith('/events')) return new Response('not found', { status: 404 });
- return new Response(JSON.stringify({ repo: { status: 'completed', rule_count: 1, commit_count: 1 } }), { status: 200 });
- }) as typeof fetch,
- });
- assert.equal(outcome, 'completed');
- assert.deepEqual(hits, ['events', 'poll']);
-});
-
-test('a silent stream counts as dropped once the keep-alives stop', async () => {
- let connections = 0;
- const outcome = await watchBuild(LINK, {
- ...NOW,
- events: true,
- idleMs: 20,
- maxReconnects: 0,
- write: () => {},
- fetchImpl: (async (u: string) => {
- if (u.endsWith('/events')) {
- connections++;
- return stream([], { end: false });
- }
- return new Response(JSON.stringify({ repo: { status: 'completed', rule_count: 3, commit_count: 1 } }), { status: 200 });
- }) as typeof fetch,
- });
- assert.equal(outcome, 'completed');
- assert.equal(connections, 1);
-});
-
-test('without the events flag nothing asks for the stream', async () => {
- const hits: string[] = [];
- await watchBuild(LINK, {
- ...NOW,
- write: () => {},
- fetchImpl: (async (u: string) => {
- hits.push(u);
- return new Response(JSON.stringify({ repo: { status: 'completed', rule_count: 1, commit_count: 1 } }), { status: 200 });
- }) as typeof fetch,
- });
- assert.ok(hits.every((u) => u.endsWith('/repo')));
-});
diff --git a/test/brain-watch.test.ts b/test/brain-watch.test.ts
deleted file mode 100644
index b9a9c162..00000000
--- a/test/brain-watch.test.ts
+++ /dev/null
@@ -1,227 +0,0 @@
-/**
- * The push now holds the line instead of handing the prompt back, so what is
- * worth testing is the thing that made holding worthwhile: that a build which
- * dies is reported, and reported at the stage it actually died at.
- */
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import { failureLines, linesFor, stagesFrom, watchBuild, type RepoState } from '../src/brain/watch.js';
-import { brainUrl } from '../src/brain/signup.js';
-
-const row = (over: Partial<RepoState> = {}): RepoState => ({
- status: 'ingesting',
- ruleCount: 0,
- commitCount: 0,
- threadCount: 0,
- ...over,
-});
-
-const stateOf = (repo: RepoState | null, id: string) => stagesFrom(repo).stages.find((s) => s.id === id)?.state;
-
-// --- where a failure lands ---------------------------------------------------
-
-// The one that matters. A repo read successfully and then lost in the miner
-// must not report itself as unreachable: that sends someone to fix repository
-// access for a problem that has nothing to do with access.
-test('a build that read the history and then died fails at the miner, not the access check', () => {
- const repo = row({
- status: 'failed',
- commitCount: 412,
- threadCount: 89,
- errorMessage: 'mine repository history: parse response: unexpected end of JSON input',
- });
- assert.equal(stateOf(repo, 'reach'), 'done');
- assert.equal(stateOf(repo, 'read'), 'done');
- assert.equal(stateOf(repo, 'mine'), 'failed');
- assert.match(stagesFrom(repo).error ?? '', /unexpected end of JSON input/);
-});
-
-test('a build that never read anything fails at the access check', () => {
- const repo = row({ status: 'failed', errorMessage: 'repo not accessible' });
- assert.equal(stateOf(repo, 'reach'), 'failed');
- assert.equal(stateOf(repo, 'mine'), 'waiting');
-});
-
-test('no stage after the failed one is left looking live', () => {
- const view = stagesFrom(row({ status: 'failed', commitCount: 10 }));
- const at = view.stages.findIndex((s) => s.state === 'failed');
- assert.ok(at >= 0);
- for (const s of view.stages.slice(at + 1)) assert.equal(s.state, 'waiting');
-});
-
-test('a failure with no message still says something', () => {
- assert.equal(stagesFrom(row({ status: 'failed' })).error, 'the read stopped before it finished');
-});
-
-test('done means the rules are in the brain, not just that the row closed', () => {
- assert.equal(stagesFrom(row({ status: 'completed', commitCount: 412, ruleCount: 0 })).done, false);
- assert.equal(stagesFrom(row({ status: 'completed', commitCount: 412, ruleCount: 42 })).done, true);
-});
-
-// --- what gets printed -------------------------------------------------------
-
-// This is a log, not a redrawn frame: a line per poll for a stage that is merely
-// still running would bury the four that matter under a hundred that do not.
-test('only finished stages print, each once, in the past tense', () => {
- const printed = new Set<string>();
- const reading = row({ commitCount: 412, threadCount: 89 });
- const first = linesFor(stagesFrom(reading), printed, reading);
- assert.deepEqual(first, [' ✓ reached the repository', ' ✓ read its history'], 'reach and read have settled; mine has not');
- assert.deepEqual(linesFor(stagesFrom(reading), printed, reading), [], 'nothing reprints');
- const done = row({ status: 'completed', commitCount: 412, threadCount: 89, ruleCount: 42 });
- const later = linesFor(stagesFrom(done), printed, done);
- assert.deepEqual(later, [' ✓ mined the first 42 rules'], 'filing is left to the closing line');
-});
-
-test('a failure says where it stopped, that nothing was lost, and the server\'s own words', () => {
- const view = stagesFrom(row({ status: 'failed', commitCount: 412, errorMessage: 'parse response: unexpected end of JSON input' }));
- assert.deepEqual(failureLines(view), [
- '✗ the build stopped while mining rules · nothing was lost — run graft trail push again',
- ' parse response: unexpected end of JSON input',
- ]);
-});
-
-// --- the watcher ------------------------------------------------------------
-
-/** A fetch that answers with each row in turn, then repeats the last. */
-function fetchSeries(rows: (Record<string, unknown> | null)[]): typeof fetch {
- let i = 0;
- return (async () => {
- const repo = rows[Math.min(i++, rows.length - 1)];
- return { ok: true, json: async () => ({ repo }) } as unknown as Response;
- }) as unknown as typeof fetch;
-}
-
-/** Like fetchSeries, but each entry is the whole response body, so a test can
- * carry the in-flight `build` counts the repo row does not have yet. */
-function fetchBodies(bodies: Record<string, unknown>[]): typeof fetch {
- let i = 0;
- return (async () => {
- const body = bodies[Math.min(i++, bodies.length - 1)];
- return { ok: true, json: async () => body } as unknown as Response;
- }) as unknown as typeof fetch;
-}
-
-const LINK = { brainId: '8f2a1c04-0000-0000-0000-000000000000', token: 'gbt_1.sig' };
-const NOW = { timeoutMs: 60_000, pollMs: 0, sleep: async () => {} };
-
-test('the watcher holds until the brain is built', async () => {
- const lines: string[] = [];
- const outcome = await watchBuild(LINK, {
- ...NOW,
- write: (l) => lines.push(l),
- fetchImpl: fetchSeries([
- { status: 'pending', rule_count: 0, commit_count: 0, thread_count: 0 },
- { status: 'ingesting', rule_count: 0, commit_count: 412, thread_count: 89 },
- { status: 'completed', rule_count: 42, commit_count: 412, thread_count: 89 },
- ]),
- });
- assert.equal(outcome, 'completed');
- assert.match(lines.join('\n'), /reached the repository/);
- assert.match(lines.join('\n'), /mined the first 42 rules/);
-});
-
-test('the watcher reports a failure rather than waiting out the clock', async () => {
- const lines: string[] = [];
- const outcome = await watchBuild(LINK, {
- ...NOW,
- write: (l) => lines.push(l),
- fetchImpl: fetchSeries([
- { status: 'ingesting', rule_count: 0, commit_count: 412, thread_count: 0 },
- { status: 'failed', rule_count: 0, commit_count: 412, thread_count: 0, error_message: 'repo job carries no history to mine' },
- ]),
- });
- assert.equal(outcome, 'failed');
- assert.match(lines.join('\n'), /carries no history to mine/);
-});
-
-// A host that is down must not be reported as a build that failed: one is our
-// problem and the other is the user's, and they lead to opposite next steps.
-test('a build it could never read is unreachable, not failed', async () => {
- const outcome = await watchBuild(LINK, {
- ...NOW,
- timeoutMs: 0,
- write: () => {},
- fetchImpl: (async () => {
- throw new Error('ECONNREFUSED');
- }) as unknown as typeof fetch,
- });
- assert.equal(outcome, 'unreachable');
-});
-
-test('a build still running when the clock runs out is a timeout, not a failure', async () => {
- const outcome = await watchBuild(LINK, {
- ...NOW,
- timeoutMs: 0,
- write: () => {},
- fetchImpl: fetchSeries([{ status: 'ingesting', rule_count: 0, commit_count: 1, thread_count: 0 }]),
- });
- assert.equal(outcome, 'timed_out');
-});
-
-// --- where the browser lands -------------------------------------------------
-
-// /brain/<id> redirects to the graph, and it redirected the moment the row
-// existed — minutes before it had any rules. Every terminal signup landed on an
-// empty visualisation of a brain that was building perfectly well.
-test('the handoff lands on the build screen, never on an empty graph', () => {
- const url = brainUrl('8f2a1c04-0000-0000-0000-000000000000', 'https://app.trailhq.com');
- assert.ok(!url.includes('/brain/'), 'must not go to the brain route, which redirects to the graph');
- assert.match(url, /\/get-started\?step=build&brain=8f2a1c04-0000-0000-0000-000000000000$/);
-});
-
-// --- slices: the prompt comes back on the first rules -------------------------
-
-// The history is mined in several calls now. The first returns in about ten
-// seconds and the rest keep going for minutes, so holding the terminal to the
-// end would be holding it through the part that neither fails nor needs
-// watching.
-test('mining is finished, for this watcher, as soon as rules are in the graph', () => {
- const midBuild = row({ status: 'ingesting', commitCount: 412, threadCount: 89, ruleCount: 0, foundSoFar: 62, filedSoFar: 12 });
- assert.equal(stateOf(midBuild, 'mine'), 'done');
- assert.equal(stateOf(midBuild, 'file'), 'doing');
- assert.equal(stagesFrom(midBuild).ready, true);
- assert.equal(stagesFrom(midBuild).done, false, 'the job has not finished; only the watching has');
-});
-
-// The count grows with every slice that lands, so printing it as a total would
-// promise history that has not been read yet.
-test('the miner count is printed as a floor, not as a total', () => {
- const view = stagesFrom(row({ status: 'ingesting', commitCount: 412, foundSoFar: 62, filedSoFar: 12 }));
- assert.equal(view.stages.find((s) => s.id === 'mine')?.detail, '62 rules so far');
-});
-
-test('nothing placed yet is not ready, however much has been read', () => {
- const view = stagesFrom(row({ status: 'ingesting', commitCount: 412, threadCount: 89, foundSoFar: 0, filedSoFar: 0 }));
- assert.equal(view.ready, false);
- assert.equal(stateOf(row({ status: 'ingesting', commitCount: 412, foundSoFar: 0 }), 'mine'), 'doing');
-});
-
-test('the watcher hands the prompt back on the first rules, while the job runs on', async () => {
- const lines: string[] = [];
- const outcome = await watchBuild(LINK, {
- ...NOW,
- write: (l) => lines.push(l),
- fetchImpl: fetchBodies([
- { repo: { status: 'pending', rule_count: 0, commit_count: 0, thread_count: 0 } },
- { repo: { status: 'ingesting', rule_count: 0, commit_count: 412, thread_count: 89 }, build: { found_so_far: 0, filed_so_far: 0 } },
- { repo: { status: 'ingesting', rule_count: 0, commit_count: 412, thread_count: 89 }, build: { found_so_far: 62, filed_so_far: 3 } },
- ]),
- });
- assert.equal(outcome, 'building');
- assert.match(lines.join('\n'), /mined the first 62 rules/);
-});
-
-// A graft pointed at a Trail that does not send the in-flight counts must fall
-// back to the old behaviour rather than read a missing field as "no rules".
-test('an older API with no build counts still waits for the finished row', async () => {
- const outcome = await watchBuild(LINK, {
- ...NOW,
- write: () => {},
- fetchImpl: fetchSeries([
- { status: 'ingesting', rule_count: 0, commit_count: 412, thread_count: 89 },
- { status: 'completed', rule_count: 42, commit_count: 412, thread_count: 89 },
- ]),
- });
- assert.equal(outcome, 'completed');
-});
diff --git a/test/claude-md-pull.test.ts b/test/claude-md-pull.test.ts
deleted file mode 100644
index 9ee79cf1..00000000
--- a/test/claude-md-pull.test.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-/**
- * `graft claude-md pull` edits a file people also edit by hand, so what matters
- * is that it touches only what a change names, never guesses when the file has
- * moved on, and never writes the same change twice.
- */
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import { applyChanges, fetchAcceptedChanges, markApplied, type ClaudeMdChange } from '../src/brain/claude-md.js';
-import type { BrainLink } from '../src/brain/link.js';
-
-const FILE = [
- '# chalk',
- '',
- 'Terminal string styling.',
- '',
- '## Commands',
- '',
- '- `npm test` runs the test suite with ava.',
- '- `npx xo` lints the code.',
- '',
- '```bash',
- '## not a heading',
- '```',
- '',
- '## Architecture',
- '',
- '- `source/index.js` builds the chainable instance.',
- '',
-].join('\n');
-
-const edit = (over: Partial<ClaudeMdChange> = {}): ClaudeMdChange => ({
- id: 'e1',
- kind: 'edit',
- heading: 'Commands',
- find: '- `npm test` runs the test suite with ava.',
- text: '- `npm test` runs xo, c8 and ava. Always run the whole script, never ava alone.',
- ...over,
-});
-const add = (over: Partial<ClaudeMdChange> = {}): ClaudeMdChange => ({
- id: 'a1',
- kind: 'add',
- heading: 'Breaking changes',
- after_heading: 'Commands',
- text: 'Every exported name is public API. Deprecate for one major first.',
- ...over,
-});
-
-test('an edit replaces only its own text, and the rest comes back byte for byte', () => {
- const r = applyChanges(FILE, [edit()]);
- assert.deepEqual(r.written.map((c) => c.id), ['e1']);
- assert.equal(r.text, FILE.replace('- `npm test` runs the test suite with ava.', edit().text));
-});
-
-test('a new section goes after the one it names, with a blank line either side', () => {
- const r = applyChanges(FILE, [add()]);
- assert.match(r.text, /- `npx xo` lints the code\.\n\n```bash\n## not a heading\n```\n\n## Breaking changes\n\nEvery exported name is public API\. Deprecate for one major first\.\n\n## Architecture/);
-});
-
-test('a new section with no anchor goes at the end', () => {
- const r = applyChanges(FILE, [add({ after_heading: '' })]);
- assert.ok(r.text.endsWith('## Breaking changes\n\nEvery exported name is public API. Deprecate for one major first.\n'));
-});
-
-test('an edit whose text is gone is skipped, not guessed at', () => {
- const moved = FILE.replace('runs the test suite with ava', 'runs everything');
- const r = applyChanges(moved, [edit()]);
- assert.equal(r.written.length, 0);
- assert.equal(r.skipped.length, 1);
- assert.equal(r.text, moved, 'the file is untouched');
-});
-
-test('a heading inside a code fence is not a section', () => {
- const r = applyChanges(FILE, [edit({ heading: 'not a heading' })]);
- assert.equal(r.skipped.length, 1);
-});
-
-test('changes already in the file are reported as present, not written again', () => {
- const once = applyChanges(FILE, [edit(), add()]).text;
- const twice = applyChanges(once, [edit(), add()]);
- assert.equal(twice.written.length, 0);
- assert.deepEqual(twice.present.map((c) => c.id).sort(), ['a1', 'e1']);
- assert.equal(twice.text, once);
-});
-
-test('an empty find appends to the end of the section', () => {
- const r = applyChanges(FILE, [edit({ find: '', text: '- `npm run bench` runs the benchmarks.' })]);
- assert.match(r.text, /```\n- `npm run bench` runs the benchmarks\.\n\n## Architecture/);
-});
-
-test('a repo with no CLAUDE.md gets one from the accepted additions', () => {
- const r = applyChanges('', [add({ after_heading: '' })]);
- assert.equal(r.text, '## Breaking changes\n\nEvery exported name is public API. Deprecate for one major first.\n');
-});
-
-test('CRLF files stay CRLF', () => {
- const crlf = FILE.replace(/\n/g, '\r\n');
- const r = applyChanges(crlf, [edit()]);
- assert.ok(!/[^\r]\n/.test(r.text), 'no bare LF introduced');
- assert.ok(r.text.includes('never ava alone.'));
-});
-
-// --- the two calls ------------------------------------------------------------
-
-const link = { brainId: 'b1', token: 'gbt_1.x', baseUrl: 'http://trail.test' } as unknown as BrainLink;
-const json = (body: unknown, status = 200) =>
- new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
-
-test('pull reads the accepted changes with the brain token', async () => {
- let seen: { url: string; auth: string } | null = null;
- const got = await fetchAcceptedChanges(link, (async (u: string, init?: RequestInit) => {
- seen = { url: u, auth: String((init?.headers as Record<string, string>).authorization) };
- return json({ path: 'CLAUDE.md', head_sha: 'abc', changes: [edit()] });
- }) as typeof fetch);
- assert.ok(!('error' in got) && got.changes.length === 1);
- assert.equal(seen!.url, 'http://trail.test/api/public/brains/b1/claude-md');
- assert.equal(seen!.auth, 'Bearer gbt_1.x');
-
- const older = await fetchAcceptedChanges(link, (async () => json({ error: 'nope' }, 404)) as typeof fetch);
- assert.ok('error' in older);
-});
-
-test('applied ids are reported in batches of at most 100', async () => {
- const bodies: string[][] = [];
- const ok = await markApplied(
- link,
- Array.from({ length: 150 }, (_, i) => `id${i}`),
- (async (_u: string, init?: RequestInit) => {
- bodies.push((JSON.parse(String(init?.body)) as { ids: string[] }).ids);
- return json({ applied: 1 });
- }) as typeof fetch,
- );
- assert.equal(ok, true);
- assert.deepEqual(bodies.map((b) => b.length), [100, 50]);
-});
diff --git a/test/legacy-args.test.ts b/test/legacy-args.test.ts
deleted file mode 100644
index b62c17e6..00000000
--- a/test/legacy-args.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * `graft brain …` and `init --brain` were renamed to `trail`. The old spellings
- * are in docs, scripts and Trail pages already open, so they must keep working
- * — and only where they are the command, never as someone's argument.
- */
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import { withLegacyNames } from '../src/legacy-args.js';
-
-const run = (...args: string[]) => withLegacyNames(['node', 'graft', ...args]).slice(2);
-
-test('graft brain … runs graft trail …', () => {
- assert.deepEqual(run('brain', 'push'), ['trail', 'push']);
- assert.deepEqual(run('trail', 'push'), ['trail', 'push']);
-});
-
-test('the command is found after global options, including ones that take a value', () => {
- assert.deepEqual(run('--dir', 'brain', 'brain', 'status'), ['--dir', 'brain', 'trail', 'status'], 'a --dir named brain stays');
- assert.deepEqual(run('--model', 'x', 'brain', 'pull'), ['--model', 'x', 'trail', 'pull']);
-});
-
-test('only the command word is renamed', () => {
- assert.deepEqual(run('ask', 'how does the brain work'), ['ask', 'how does the brain work']);
- assert.deepEqual(run('grep', 'brain'), ['grep', 'brain']);
-});
-
-test('init --brain runs init --trail, in both forms', () => {
- assert.deepEqual(run('init', '--brain', 'id:tok'), ['init', '--trail', 'id:tok']);
- assert.deepEqual(run('init', '--brain=id:tok'), ['init', '--trail=id:tok']);
-});
diff --git a/test/telemetry-contract.test.ts b/test/telemetry-contract.test.ts
index adff8d2e..82a471c2 100644
--- a/test/telemetry-contract.test.ts
+++ b/test/telemetry-contract.test.ts
@@ -75,11 +75,10 @@ test('every event carries the common properties, and no identifier beyond them',
// Pinned rather than counted, so adding an event is a deliberate edit here and
// a matching row in TELEMETRY.md, never something that arrives with a feature.
-test('the contract lists exactly the nineteen documented events', () => {
+test('the contract lists exactly the sixteen documented events', () => {
assert.deepEqual(Object.keys(EVENTS).sort(), [
'brain_signup_opened', 'brain_signup_settled', 'build_completed', 'build_failed',
'cold_start', 'first_run', 'init_completed', 'install', 'learning_reused', 'learnings_committed', 'note_saved', 'query', 'repo_seen', 'session_summary', 'skills_folded', 'takeaway_saved',
- 'trail_autopush', 'trail_pulled', 'trail_watch_exit',
]);
});
@@ -187,7 +186,7 @@ test('brain signup: the outcome is a category, never the sentence the user saw',
{
outcome: 'timed_out',
duration_bucket: durationBucket(5 * 60 * 1000),
- error: 'timed out waiting for the browser — run `graft trail push` again',
+ error: 'timed out waiting for the browser — run `trail login` again',
},
{ home, env: OPEN },
);
@@ -211,51 +210,3 @@ test('brain signup: both events are in the contract', () => {
assert.ok(EVENTS.brain_signup_opened);
assert.ok(EVENTS.brain_signup_settled);
});
-
-// --- trail pull ---
-
-test('trail pull: counts travel as buckets, and a path never rides along', () => {
- const home = sandbox('tel-trail-pulled');
- const ev = track(
- 'trail_pulled',
- { outcome: 'written', kinds: 'agents_md,claude_md', files_bucket: '1-4', changes_bucket: '5-19', skipped_bucket: '0', suggested_bucket: '20-49', path: 'web/CLAUDE.md' },
- { home, env: OPEN },
- );
- assert.equal(ev?.properties.outcome, 'written');
- assert.equal(ev?.properties.kinds, 'agents_md,claude_md');
- assert.equal(ev?.properties.changes_bucket, '5-19');
- assert.equal(ev?.properties.suggested_bucket, '20-49');
- assert.equal(ev?.properties.path, undefined);
-});
-
-// --- the trail watcher and the background push ---
-
-test('trail_watch_exit carries buckets and a reason, never the files or the link', () => {
- const home = sandbox('tel-trail-watch');
- const ev = track(
- 'trail_watch_exit',
- {
- reason: 'accepted',
- suggested_bucket: countBucket(9),
- accepted_bucket: countBucket(3),
- duration_bucket: durationBucket(61_000),
- files: 'CLAUDE.md (Commands)',
- review_url: 'https://app.trailhq.com/brain/b1/context-files',
- },
- { home, env: OPEN },
- );
- assert.equal(ev?.properties.reason, 'accepted');
- assert.equal(ev?.properties.suggested_bucket, '5-19');
- assert.equal(ev?.properties.accepted_bucket, '1-4');
- assert.equal(ev?.properties.duration_bucket, '30s-2m');
- assert.equal(JSON.stringify(ev).includes('CLAUDE.md'), false);
- assert.equal(JSON.stringify(ev).includes('trailhq'), false);
-});
-
-test('trail_autopush carries only whether it started and why not', () => {
- const home = sandbox('tel-trail-autopush');
- const ev = track('trail_autopush', { outcome: 'skipped', reason: 'throttled', head: 'a'.repeat(40) }, { home, env: OPEN });
- assert.equal(ev?.properties.outcome, 'skipped');
- assert.equal(ev?.properties.reason, 'throttled');
- assert.equal(ev?.properties.head, undefined);
-});
diff --git a/test/trail-name.test.ts b/test/trail-name.test.ts
index 52fc22cd..2901b0c4 100644
--- a/test/trail-name.test.ts
+++ b/test/trail-name.test.ts
@@ -29,15 +29,11 @@ test("unset means graft: anything that loads cli.js directly was wired by an old
});
test("cmd spells a graft command the way the running name does", () => {
- for (const s of ["graft ask", "graft check", "graft trail push", "graft build --deep"]) assert.equal(cmd(s, "graft"), s);
+ for (const s of ["graft ask", "graft check", "graft build --deep"]) assert.equal(cmd(s, "graft"), s);
assert.equal(cmd("graft ask", "trail"), "trail ask");
assert.equal(cmd("graft build --deep", "trail"), "trail build --deep");
assert.equal(cmd("graft check", "trail"), "trail build --check");
assert.equal(cmd("graft stats", "trail"), "trail status");
- assert.equal(cmd("graft trail status", "trail"), "trail status");
- assert.equal(cmd("graft trail push", "trail"), "trail push");
- assert.equal(cmd("graft trail connect", "trail"), "trail login");
- assert.equal(cmd("graft trail disconnect", "trail"), "trail logout");
// A prefix only matches a whole word: `graft checkout` is not `graft check`.
assert.equal(cmd("graft checkout", "trail"), "trail checkout");
});
@@ -147,11 +143,12 @@ test("trail --help groups the commands, and lists the workspace ones only once s
for (const c of ["workspace", "login", "logout"]) assert.match(on.out, new RegExp(`^ ${c} `, "m"), c);
});
-test("graft --help keeps its old flat list, including check and the trail group", () => {
+test("graft --help keeps its old flat list, including check, without the trail group", () => {
const r = run("graft", ["--help"], scratchHome());
assert.equal(r.status, 0);
assert.match(r.out, /^Usage: graft /m);
- for (const c of ["check", "stats", "viz", "trail"]) assert.match(r.out, new RegExp(`^ ${c} `, "m"), c);
+ for (const c of ["check", "stats", "viz"]) assert.match(r.out, new RegExp(`^ ${c} `, "m"), c);
+ assert.doesNotMatch(r.out, /^ trail /m);
assert.ok(!r.out.includes("Workspace ·"));
});
@@ -195,23 +192,12 @@ test("trail status puts the code map on one screen, and the workspace only once
assert.equal(json.workspace, null);
});
-test("old spellings keep working under trail: trail trail status, trail brain status, trail stats", () => {
+test("trail stats still works under trail", () => {
const home = scratchHome();
const d = builtRepo();
run("trail", ["build", d], home);
- for (const args of [["trail", "status", d], ["brain", "status", d], ["stats", d]]) {
- const r = run("trail", args, home);
- assert.equal(r.status, 0, `${args.join(" ")}: ${r.err}`);
- }
- assert.match(run("trail", ["trail", "status", d], home).out, /^code map/m);
-});
-
-test("graft trail status is unchanged", () => {
- const home = scratchHome();
- const d = builtRepo();
- const r = run("graft", ["trail", "status", d], home);
- assert.equal(r.status, 0);
- assert.match(r.err, /no brain attached — run `graft trail connect <brainId>:<token>`/);
+ const r = run("trail", ["stats", d], home);
+ assert.equal(r.status, 0, r.err);
});
test("the savings footer says [trail] under trail and [graft] under graft", () => {
diff --git a/test/trail-session-start.test.ts b/test/trail-session-start.test.ts
deleted file mode 100644
index fd1c5c9c..00000000
--- a/test/trail-session-start.test.ts
+++ /dev/null
@@ -1,263 +0,0 @@
-/**
- * The session-start hook's two trail jobs: one line of context when the trail
- * has something waiting, and a background push at most once a day when HEAD has
- * moved. Both run inside a hook, so the tests are mostly about when they do
- * nothing — no trail, nothing waiting, Trail too slow, HEAD where it was, a push
- * already today — and about never reaching the network or spawning for a repo
- * without a trail.
- */
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
-import { join } from 'node:path';
-import { main, trailAtSessionStart } from '../src/claude/hooks.js';
-import {
- AUTOPUSH_INTERVAL_MS,
- decideAutopush,
- maybeAutopush,
- readTrailPushState,
- recordTrailPush,
- trailPushStatePath,
-} from '../src/brain/autopush.js';
-import { writeLink, type BrainLink } from '../src/brain/link.js';
-import { patchBuildConfig } from '../src/util/state.js';
-import { tmpRepo } from './helpers.js';
-
-const link: BrainLink = { brainId: 'b1', token: 'gbt_1.x', baseUrl: 'http://trail.test' };
-const json = (body: unknown, status = 200) =>
- new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
-
-function linkedRepo(tag: string): string {
- const root = tmpRepo(tag);
- writeLink(root, link);
- return root;
-}
-
-/** A Trail with `suggested` CLAUDE.md suggestions and these accepted changes. */
-function fakeTrail(suggested: number, claudeMd: unknown[] = []) {
- let calls = 0;
- const f = (async (u: string) => {
- calls++;
- const path = new URL(u).pathname;
- if (path.endsWith('/claude-md')) return json({ path: 'CLAUDE.md', head_sha: 'abc', changes: claudeMd });
- if (path.endsWith('/context-files')) return json({ head_sha: 'abc', files: [] });
- if (path.endsWith('/repo')) return json({ repo: { status: 'completed', rule_count: 3 }, claude_md: { changes: suggested } });
- return json({}, 500);
- }) as typeof fetch;
- return { f, calls: () => calls };
-}
-
-/** Autopush deps that never touch git or spawn anything. */
-function noPush() {
- const started: string[] = [];
- return { started, deps: { head: () => 'a'.repeat(40), start: (r: string) => (started.push(r), true), env: {} } };
-}
-
-// --- the context line ---------------------------------------------------------
-
-test('accepted changes waiting: the line names the files and asks about a pull', async () => {
- const root = linkedRepo('ss-accepted');
- writeFileSync(join(root, 'CLAUDE.md'), '# app\n\n## Commands\n\n- `npm test`\n');
- const { f } = fakeTrail(9, [
- { id: 'm1', kind: 'edit', heading: 'Commands', find: '', text: '- lint' },
- { id: 'm2', kind: 'add', heading: 'Testing', after_heading: 'Commands', text: 'node:test' },
- ]);
- const line = await trailAtSessionStart(root, { fetchImpl: f, autopush: noPush().deps });
- assert.equal(line, 'Trail: 2 accepted changes are waiting (CLAUDE.md: Commands, Testing). Ask the user whether to run graft trail pull.');
-});
-
-test('only suggestions: the line points at the review page', async () => {
- const root = linkedRepo('ss-suggested');
- const { f } = fakeTrail(5);
- const line = await trailAtSessionStart(root, { fetchImpl: f, autopush: noPush().deps });
- assert.match(line ?? '', /^Trail: 5 suggestions are waiting for review at \S+\/brain\/b1\/context-files\.$/);
-});
-
-test('the same suggestions next session say nothing; more say only how many are new', async () => {
- const root = linkedRepo('ss-repeat');
- const push = noPush().deps;
- const first = await trailAtSessionStart(root, { fetchImpl: fakeTrail(5).f, autopush: push });
- assert.match(first ?? '', /^Trail: 5 suggestions are waiting for review at /, 'first check with nothing stored: mentioned once');
- assert.equal(readTrailPushState(root).seenSuggested, 5);
-
- assert.equal(await trailAtSessionStart(root, { fetchImpl: fakeTrail(5).f, autopush: push }), null, 'unchanged: no nag');
-
- const grown = await trailAtSessionStart(root, { fetchImpl: fakeTrail(8).f, autopush: push });
- assert.match(grown ?? '', /^Trail: 3 new suggestions since your last session are waiting for review at \S+\/brain\/b1\/context-files\.$/);
- assert.equal(readTrailPushState(root).seenSuggested, 8);
-
- const one = await trailAtSessionStart(root, { fetchImpl: fakeTrail(9).f, autopush: push });
- assert.match(one ?? '', /^Trail: 1 new suggestion since your last session is waiting for review at /);
- assert.equal(await trailAtSessionStart(root, { fetchImpl: fakeTrail(9).f, autopush: push }), null);
-});
-
-test('accepted changes are mentioned every session, and still move the suggestions mark', async () => {
- const root = linkedRepo('ss-accepted-repeat');
- const accepted = [{ id: 'm1', kind: 'add', heading: 'Money', after_heading: '', text: 'Integer cents.' }];
- const push = noPush().deps;
- for (let i = 0; i < 2; i++) {
- const line = await trailAtSessionStart(root, { fetchImpl: fakeTrail(6, accepted).f, autopush: push });
- assert.equal(line, 'Trail: 1 accepted change is waiting (CLAUDE.md: Money). Ask the user whether to run graft trail pull.');
- }
- assert.equal(readTrailPushState(root).seenSuggested, 6);
- // Pulled since: the six suggestions were already known, so nothing to say.
- assert.equal(await trailAtSessionStart(root, { fetchImpl: fakeTrail(6).f, autopush: push }), null);
-});
-
-test('a failed check leaves the suggestions mark where it was', async () => {
- const root = linkedRepo('ss-mark-kept');
- const push = noPush().deps;
- await trailAtSessionStart(root, { fetchImpl: fakeTrail(4).f, autopush: push });
- const down = (async () => {
- throw new TypeError('fetch failed');
- }) as unknown as typeof fetch;
- assert.equal(await trailAtSessionStart(root, { fetchImpl: down, autopush: push }), null);
- assert.equal(readTrailPushState(root).seenSuggested, 4);
- assert.match((await trailAtSessionStart(root, { fetchImpl: fakeTrail(7).f, autopush: push })) ?? '', /^Trail: 3 new suggestions/);
-});
-
-test('nothing waiting: no line', async () => {
- const root = linkedRepo('ss-zero');
- assert.equal(await trailAtSessionStart(root, { fetchImpl: fakeTrail(0).f, autopush: noPush().deps }), null);
-});
-
-test('no trail attached: no line, no request, no push', async () => {
- const root = tmpRepo('ss-unlinked');
- const { f, calls } = fakeTrail(5);
- const push = noPush();
- assert.equal(await trailAtSessionStart(root, { fetchImpl: f, autopush: push.deps }), null);
- assert.equal(calls(), 0);
- assert.deepEqual(push.started, []);
- assert.equal(existsSync(trailPushStatePath(root)), false);
-});
-
-test('a Trail that does not answer costs the cap and no more', async () => {
- const root = linkedRepo('ss-slow');
- // Ignores the abort signal on purpose: the race, not the abort, is the guarantee.
- const never = (() => new Promise<Response>(() => undefined)) as unknown as typeof fetch;
- const t0 = Date.now();
- const line = await trailAtSessionStart(root, { fetchImpl: never, capMs: 50, autopush: noPush().deps });
- assert.equal(line, null);
- assert.ok(Date.now() - t0 < 1000, `took ${Date.now() - t0} ms`);
-});
-
-test('a failing Trail is a missing line, never an error', async () => {
- const root = linkedRepo('ss-down');
- const down = (async () => {
- throw new TypeError('fetch failed');
- }) as unknown as typeof fetch;
- assert.equal(await trailAtSessionStart(root, { fetchImpl: down, autopush: noPush().deps }), null);
-});
-
-test('session-start puts the trail line in the context it emits', async () => {
- const root = linkedRepo('ss-main');
- const realFetch = globalThis.fetch;
- const writes: string[] = [];
- const realWrite = process.stdout.write.bind(process.stdout);
- globalThis.fetch = fakeTrail(3).f;
- process.env.CLAUDE_PROJECT_DIR = root;
- process.env.GRAFT_TEST_STDIN = '{}';
- // Off, so this end-to-end run never spawns a real push.
- process.env.GRAFT_TRAIL_AUTOPUSH = '0';
- (process.stdout as { write: unknown }).write = (chunk: string) => (writes.push(String(chunk)), true);
- try {
- await main('session-start');
- } finally {
- (process.stdout as { write: unknown }).write = realWrite;
- globalThis.fetch = realFetch;
- delete process.env.GRAFT_TEST_STDIN;
- delete process.env.GRAFT_TRAIL_AUTOPUSH;
- }
- const out = JSON.parse(writes.join(''));
- assert.equal(out.hookSpecificOutput.hookEventName, 'SessionStart');
- assert.match(out.hookSpecificOutput.additionalContext, /Trail: 3 suggestions are waiting for review at /);
-});
-
-// --- the background push --------------------------------------------------------
-
-const HEAD = 'a'.repeat(40);
-const NEXT = 'b'.repeat(40);
-const NOW = 1_700_000_000_000;
-
-test('decideAutopush: every reason not to push, and the one to', () => {
- const base = { linked: true, enabled: true, head: NEXT, state: {}, now: NOW };
- assert.deepEqual(decideAutopush({ ...base, linked: false }), { start: false, reason: 'no_trail' });
- assert.deepEqual(decideAutopush({ ...base, enabled: false }), { start: false, reason: 'disabled' });
- assert.deepEqual(decideAutopush({ ...base, head: null }), { start: false, reason: 'no_head' });
- assert.deepEqual(decideAutopush({ ...base, state: { pushedHead: NEXT } }), { start: false, reason: 'head_unchanged' });
- assert.deepEqual(decideAutopush({ ...base, state: { autoPushHead: NEXT, autoPushAt: 0 } }), { start: false, reason: 'head_unchanged' });
- assert.deepEqual(
- decideAutopush({ ...base, state: { pushedHead: HEAD, autoPushAt: NOW - AUTOPUSH_INTERVAL_MS + 1 } }),
- { start: false, reason: 'throttled' },
- );
- assert.deepEqual(decideAutopush({ ...base, state: { pushedHead: HEAD, autoPushAt: NOW - AUTOPUSH_INTERVAL_MS } }), { start: true, head: NEXT });
- assert.deepEqual(decideAutopush(base), { start: true, head: NEXT }, 'no push recorded counts as moved');
-});
-
-test('autopush starts once, stamps first, and is then throttled for a day', () => {
- const root = linkedRepo('ap-throttle');
- const started: string[] = [];
- const start = (r: string) => (started.push(r), true);
- recordTrailPush(root, HEAD, NOW - 3 * AUTOPUSH_INTERVAL_MS);
-
- assert.deepEqual(maybeAutopush(root, { env: {}, now: NOW, head: () => NEXT, start }), { start: true, head: NEXT });
- assert.deepEqual(started, [root]);
- assert.equal(readTrailPushState(root).autoPushAt, NOW);
- assert.equal(readTrailPushState(root).autoPushHead, NEXT);
-
- // Another commit an hour later: still today's push.
- const later = 'c'.repeat(40);
- assert.deepEqual(maybeAutopush(root, { env: {}, now: NOW + 3_600_000, head: () => later, start }), { start: false, reason: 'throttled' });
- // A day on, it may go again.
- assert.deepEqual(maybeAutopush(root, { env: {}, now: NOW + AUTOPUSH_INTERVAL_MS, head: () => later, start }), { start: true, head: later });
- assert.equal(started.length, 2);
-});
-
-test('autopush skips a HEAD the last push already covered', () => {
- const root = linkedRepo('ap-unchanged');
- recordTrailPush(root, HEAD, NOW - 5 * AUTOPUSH_INTERVAL_MS);
- const started: string[] = [];
- const d = maybeAutopush(root, { env: {}, now: NOW, head: () => HEAD, start: (r) => (started.push(r), true) });
- assert.deepEqual(d, { start: false, reason: 'head_unchanged' });
- assert.deepEqual(started, []);
-});
-
-test('autopush never runs for a repo without a saved trail', () => {
- const unlinked = tmpRepo('ap-none');
- let headRead = false;
- const start = () => {
- throw new Error('must not start');
- };
- const head = () => ((headRead = true), HEAD);
- assert.deepEqual(maybeAutopush(unlinked, { env: {}, now: NOW, head, start }), { start: false, reason: 'no_trail' });
- assert.equal(headRead, false, 'not even HEAD is read');
- assert.equal(existsSync(trailPushStatePath(unlinked)), false);
-
- // A link from the environment alone is CI's way of attaching a trail: no push from a hook there either.
- process.env.GRAFT_BRAIN_TOKEN = 'gbt_env';
- process.env.GRAFT_BRAIN_ID = 'b-env';
- try {
- assert.deepEqual(maybeAutopush(unlinked, { env: {}, now: NOW, head, start }), { start: false, reason: 'no_trail' });
- } finally {
- delete process.env.GRAFT_BRAIN_TOKEN;
- delete process.env.GRAFT_BRAIN_ID;
- }
-});
-
-test('autopush is off with GRAFT_TRAIL_AUTOPUSH=0 or trailAutoPush: false', () => {
- const root = linkedRepo('ap-off');
- const start = () => {
- throw new Error('must not start');
- };
- assert.deepEqual(maybeAutopush(root, { env: { GRAFT_TRAIL_AUTOPUSH: '0' }, now: NOW, head: () => NEXT, start }), { start: false, reason: 'disabled' });
- patchBuildConfig(root, { trailAutoPush: false });
- assert.deepEqual(maybeAutopush(root, { env: {}, now: NOW, head: () => NEXT, start }), { start: false, reason: 'disabled' });
- assert.equal(readTrailPushState(root).autoPushAt, undefined, 'nothing stamped when off');
-});
-
-test('a spawn that fails is reported, and still counts as today\'s attempt', () => {
- const root = linkedRepo('ap-spawn-fail');
- mkdirSync(join(root, '.graft'), { recursive: true });
- assert.deepEqual(maybeAutopush(root, { env: {}, now: NOW, head: () => NEXT, start: () => false }), { start: false, reason: 'spawn_failed' });
- assert.equal(readTrailPushState(root).autoPushAt, NOW);
-});