Skip to content

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

feat(trail): graft trail watch and a session-start trail check with daily background push

anirudhkumar-nanonetsd34c115155f4
diff --git a/README.md b/README.md
index d4b2d057..709a2768 100644
--- a/README.md
+++ b/README.md
@@ -329,6 +329,7 @@ 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"/>
@@ -389,6 +390,13 @@ 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 166788ee..0b535b5a 100644
--- a/TELEMETRY.md
+++ b/TELEMETRY.md
@@ -49,6 +49,8 @@ The events:
| `brain_signup_opened` | `mode` (`terminal`/`agent`) | `graft trail push` on a repo with no brain opens your browser to make one |
| `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`), `duration_bucket` | That handoff ends, one way or the other — for an agent-run push, each of its runs |
| `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 |
| `session_summary` | `graft_reads_bucket`, `source_reads_bucket`, `saved_tokens_bucket`, `graft_turns_bucket`, `reported_turns_bucket` | Once, after an agent session ends |
Two rules govern every value above, and both are enforced in code rather than by
diff --git a/src/brain/autopush.ts b/src/brain/autopush.ts
new file mode 100644
index 00000000..9891f0bb
--- /dev/null
+++ b/src/brain/autopush.ts
@@ -0,0 +1,269 @@
+/**
+ * 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
index 8267861e..2a1e912a 100644
--- a/src/brain/claude-md.ts
+++ b/src/brain/claude-md.ts
@@ -51,7 +51,7 @@ export interface ApplyResult {
export async function fetchAcceptedChanges(
link: BrainLink,
fetchImpl: typeof fetch = fetch,
-): Promise<ClaudeMdPull | { error: string; unsupported?: boolean }> {
+): 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, {
@@ -62,7 +62,9 @@ export async function fetchAcceptedChanges(
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 };
}
- if (!res.ok) return { error: `Trail refused the pull: ${res.status} ${body.slice(0, 200)}` };
+ // 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) {
diff --git a/src/brain/context-files.ts b/src/brain/context-files.ts
index c727c074..804698ce 100644
--- a/src/brain/context-files.ts
+++ b/src/brain/context-files.ts
@@ -93,7 +93,7 @@ export function readersOf(kind: string, wired: readonly string[]): string[] {
export async function fetchContextFiles(
link: BrainLink,
fetchImpl: typeof fetch = fetch,
-): Promise<ContextFilesPull | { unsupported: true } | { error: string }> {
+): 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, {
@@ -102,7 +102,7 @@ export async function fetchContextFiles(
});
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)}` };
+ 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 {
diff --git a/src/brain/pull.ts b/src/brain/pull.ts
index f91ba6e8..00bbd914 100644
--- a/src/brain/pull.ts
+++ b/src/brain/pull.ts
@@ -26,7 +26,7 @@ import {
} from "./context-files.js";
import type { BrainLink } from "./link.js";
import { reviewUrl } from "./signup.js";
-import { fetchRepoState, type Suggestions } from "./watch.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";
@@ -123,12 +123,78 @@ export function suggestedLine(suggested: { count: number; whose: string }, accep
}
/** Everything the pull will write, file by file, with where each change came from. */
-interface Planned {
+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.
@@ -177,36 +243,13 @@ export async function runTrailPull(repo: string, link: BrainLink, opts: PullOpti
}
// 2. Accepted changes: the root CLAUDE.md, then every other context file.
- const planned: Planned[] = [];
- let accepted = 0;
-
- const md = await fetchAcceptedChanges(link, fetchImpl);
- if ("error" in md) {
- if (!md.unsupported) {
- write(`✗ ${md.error}`);
- code = 1;
- }
- } 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, opts.wired)) {
- accepted += file.changes.length;
- planned.push({ plan: planContextFile(repo, file), source: "claude-md", kind: file.kind });
- }
- }
-
- const ctx = await fetchContextFiles(link, fetchImpl);
- if ("error" in ctx) {
- write(`✗ ${ctx.error}`);
+ const { planned, accepted, suggested: counted, errors } = await gatherPull(repo, link, opts.wired, fetchImpl, repoState);
+ for (const e of errors) {
+ write(`✗ ${e.message}`);
code = 1;
- } else if (!("unsupported" in ctx)) {
- for (const file of ctx.files) {
- if (file.changes.length === 0 || !readByWired(file.kind, opts.wired)) continue;
- accepted += file.changes.length;
- planned.push({ plan: planContextFile(repo, file), source: "context-files", kind: file.kind });
- }
}
- const suggested = suggestedFor((await repoState)?.suggestions, opts.wired);
+ const suggested = counted ?? { count: 0, whose: "" };
const waiting = suggestedLine(suggested, accepted);
if (accepted === 0) {
diff --git a/src/brain/watch-trail.ts b/src/brain/watch-trail.ts
new file mode 100644
index 00000000..0c616865
--- /dev/null
+++ b/src/brain/watch-trail.ts
@@ -0,0 +1,381 @@
+/**
+ * `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: 60_000, settleMs: 60_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)));
+ const fetchImpl = 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}.`;
+}
diff --git a/src/claude/hooks.ts b/src/claude/hooks.ts
index 6bf7a3fb..21977973 100644
--- a/src/claude/hooks.ts
+++ b/src/claude/hooks.ts
@@ -13,6 +13,10 @@ 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';
/** Prompts shorter than this never trigger retrieval — they are almost always
* conversational ("yes go ahead", "thanks") and the coverage gate can't judge
@@ -391,19 +395,88 @@ 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);
+ }
+}
+
export async function main(event: string): Promise<void> {
const input = readStdin();
const dir = projectDir(input);
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 — a hook must never touch the network; the CLI and the MCP
- // server fill that cache, this only reads it.
+ // background:false — the registry check stays off the network here; the CLI
+ // and the MCP server fill that cache, this only reads it.
const upkeep = runUpkeep(dir, runningVersion(), { background: false }).lines;
// Roll up any session that ended since we were last here. Queue-only — the
- // hook still touches no network; the CLI or the MCP server sends it later.
+ // hook still sends nothing; the CLI or the MCP server sends it later.
flushClosedSessions(dir);
+ 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 f162d804..54e97a9f 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -24,6 +24,7 @@ import {
buildEarlyDigest,
buildLocalDigest,
fetchExpectedRepo,
+ pickedAgents,
pushContext,
pushDigest,
pushEarlyDigest,
@@ -46,6 +47,16 @@ import {
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 { contextDirFor } from "./context/node-file.js";
import { loadGraphCached } from "./graph/load.js";
@@ -1569,6 +1580,78 @@ async function runTrailPullCommand(dir: string, opts: { dryRun?: boolean }): Pro
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;
+}
+
+brain
+ .command("watch")
+ .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);
+ },
+ );
+
brain
.command("push")
.description("Read THIS repo on your machine and build its trail — no GitHub App, works on private repos")
@@ -1589,6 +1672,13 @@ brain
// 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 — graft can only push a GitHub repository today");
@@ -1677,6 +1767,9 @@ brain
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(
diff --git a/src/telemetry/contract.ts b/src/telemetry/contract.ts
index e44d6e11..7a25903f 100644
--- a/src/telemetry/contract.ts
+++ b/src/telemetry/contract.ts
@@ -65,6 +65,15 @@ export const EVENTS: Record<string, ReadonlySet<string>> = {
* 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']),
/** One closed agent session, summarised. `graft_reads` vs `source_reads` is
* the single number that says whether an agent prefers graft to grep; the two
* `*_turns` buckets are the follow-up question — of the turns that used graft,
@@ -137,6 +146,12 @@ export type BrainSignupOutcome = (typeof BRAIN_SIGNUP_OUTCOMES)[number];
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;
diff --git a/src/util/state.ts b/src/util/state.ts
index a83aec68..93f51646 100644
--- a/src/util/state.ts
+++ b/src/util/state.ts
@@ -111,6 +111,10 @@ export interface BuildConfig {
* 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-trail-watch.test.ts b/test/brain-trail-watch.test.ts
new file mode 100644
index 00000000..1d4307ea
--- /dev/null
+++ b/test/brain-trail-watch.test.ts
@@ -0,0 +1,214 @@
+/**
+ * `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,
+} 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/);
+});
diff --git a/test/telemetry-contract.test.ts b/test/telemetry-contract.test.ts
index 1d32b823..9f7aaa60 100644
--- a/test/telemetry-contract.test.ts
+++ b/test/telemetry-contract.test.ts
@@ -75,10 +75,11 @@ 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 ten documented events', () => {
+test('the contract lists exactly the twelve documented events', () => {
assert.deepEqual(Object.keys(EVENTS).sort(), [
'brain_signup_opened', 'brain_signup_settled', 'build_completed', 'build_failed',
- 'first_run', 'init_completed', 'install', 'query', 'session_summary', 'trail_pulled',
+ 'first_run', 'init_completed', 'install', 'query', 'session_summary', 'trail_autopush', 'trail_pulled',
+ 'trail_watch_exit',
]);
});
@@ -226,3 +227,35 @@ test('trail pull: counts travel as buckets, and a path never rides along', () =>
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-session-start.test.ts b/test/trail-session-start.test.ts
new file mode 100644
index 00000000..fd1c5c9c
--- /dev/null
+++ b/test/trail-session-start.test.ts
@@ -0,0 +1,263 @@
+/**
+ * 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);
+});