Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
Trail-code 0.22.0: publish as @trailhq/trail-code, keep @nanonets/graft updating (#595)
Shrish Dwivedid45a801b0a3a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5ef248a3..46786c86 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,30 @@# Changelog+## 0.22.0++graft is now **Trail-code**. The same build ships as two packages:+`@trailhq/trail-code` (the `trail` command) and `@nanonets/graft` (the `graft`+command, unchanged). Both keep getting every release.++### Added++- **`npm install -g @trailhq/trail-code`** gives you the `trail` command: the+ code map plus learnings your team shares in `.trail/`.+- **`graft upgrade` adds `trail` alongside graft**, and the next Claude Code+ session in a graft-wired repo moves it to trail by itself.+- **The agent passes the news on**: on a machine with graft and no trail,+ Claude Code is told once a week to mention that `graft upgrade` adds trail.++### Fixed++- **Each Claude Code hook answers once**, not from both the repo's and+ `~/.claude`'s copies, so learnings no longer arrive twice per prompt.+- **Hook shims find `@trailhq/trail-code`**, and `trail` warns in a repo whose+ older graft hooks can't reach it.+- **No crash on npm 12**, which skips the grammars' install scripts: grammars+ load per language and fall back to WASM.+- The package points at `github.com/trailhq/Trail-Code`.+## 0.19.0### Addeddiff --git a/CREDITS.md b/CREDITS.mdindex 9676403d..4cf0b6db 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -2,7 +2,7 @@## Language support-graft's multi-language support was shaped by community contributors who opened+The graft map's multi-language support was shaped by community contributors who openedlanguage pull requests. That wave of one-language-at-a-time PRs is exactly whatmotivated the generic breadth tier (one tree-sitter grammar + `tags.scm` perlanguage) that now covers most of them. With gratitude to:diff --git a/README.md b/README.mdindex cf75b0fe..10fdeae6 100644--- a/README.md+++ b/README.md@@ -5,264 +5,507 @@<img src="assets/trail-code-banner.png" alt="Trail-code (previously graft), by Trail. A map of a codebase, with one team decision pinned to it: keep retries at 4." width="100%"/></picture>-### Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.+### The self-learning context layer for coding agents.-<a href="https://trendshift.io/repositories/92209?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-92209" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/92209/daily?language=TypeScript" alt="trailhq/Graft | Trendshift" width="250" height="55"/></a>+Trail-code gives Claude Code, Cursor, Codex and other coding agents a map of your code, and what your team has learned about it.++| | Code map (previously graft) | Learnings |+|---|---|---|+| **What is it?** | An index of your code: every function and who calls it, so your agent sees what a change can break | What you, your agents and your team have learned and decided |+| **What does it do for your agent?** | Takes it straight to the right files | Lets it pick up where you and your team left off |+| **Where does it come from?** | Your code, read on your machine | Your conversations, as you work |++<a href="https://trendshift.io/repositories/92209?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-92209" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/92209/daily?language=TypeScript" alt="trailhq/Trail-Code | Trendshift" width="250" height="55"/></a><p>- <a href="https://github.com/NanoNets/Graft"><img src="https://img.shields.io/github/stars/NanoNets/Graft?style=for-the-badge&logo=github&logoColor=white&label=Star%20on%20GitHub&color=FFC83D" /></a>+ <a href="https://github.com/trailhq/Trail-Code"><img src="https://img.shields.io/github/stars/trailhq/Trail-Code?style=for-the-badge&logo=github&logoColor=white&label=Star%20on%20GitHub&color=FFC83D" /></a><a href="https://trailhq.com/graft"><img src="https://img.shields.io/badge/website-trailhq.com/graft-E5484D?style=for-the-badge" /></a><a href="https://discord.gg/zxmKweAA29"><img src="https://img.shields.io/badge/Discord-join-5865F2?style=for-the-badge&logo=discord&logoColor=white" /></a>- <a href="https://www.npmjs.com/package/@nanonets/graft"><img src="https://img.shields.io/npm/v/%40nanonets%2Fgraft?style=for-the-badge&logo=npm&logoColor=white&label=npm" /></a>- <a href="https://www.npmjs.com/package/@nanonets/graft"><img src="https://img.shields.io/npm/dm/%40nanonets%2Fgraft?style=for-the-badge&logo=npm&logoColor=white&label=downloads" /></a>- <a href="https://nodejs.org"><img src="https://img.shields.io/node/v/%40nanonets%2Fgraft?style=for-the-badge&logo=nodedotjs&logoColor=white" /></a>+ <a href="https://www.npmjs.com/package/@trailhq/trail-code"><img src="https://img.shields.io/npm/v/%40trailhq%2Ftrail-code?style=for-the-badge&logo=npm&logoColor=white&label=npm" /></a>+ <a href="https://www.npmjs.com/package/@trailhq/trail-code"><img src="https://img.shields.io/npm/dm/%40trailhq%2Ftrail-code?style=for-the-badge&logo=npm&logoColor=white&label=downloads" /></a>+ <a href="https://nodejs.org"><img src="https://img.shields.io/node/v/%40trailhq%2Ftrail-code?style=for-the-badge&logo=nodedotjs&logoColor=white" /></a><img src="https://img.shields.io/badge/TypeScript-strict-3178C6?style=for-the-badge&logo=typescript&logoColor=white" /><img src="https://img.shields.io/badge/License-MIT-20C997?style=for-the-badge" /><a href="TELEMETRY.md"><img src="https://img.shields.io/badge/telemetry-anonymous%2C%20opt--out-546FFF?style=for-the-badge" /></a>- <a href="https://scorecard.dev/viewer/?uri=github.com/NanoNets/Graft"><img src="https://img.shields.io/ossf-scorecard/github.com/NanoNets/Graft?style=for-the-badge&label=openssf%20scorecard" /></a>- <a href="https://app.trailhq.com/get-started?step=repo"><img src="https://img.shields.io/badge/Trail-try%20it-E5484D?style=for-the-badge&logoColor=white" /></a>+ <a href="https://scorecard.dev/viewer/?uri=github.com/trailhq/Trail-Code"><img src="https://img.shields.io/ossf-scorecard/github.com/trailhq/Trail-Code?style=for-the-badge&label=openssf%20scorecard" /></a></p>-### Up to **4× cheaper** and **3× faster**, with better or no loss of correctness.+### **46% fewer tool calls**, **60% less time**, and more real issues solved.-| Metric | Cold Claude Code | Claude Code with graft |+| | Cold agent | Agent with the graft map ||---|---|---|-| Tool-call reduction | Baseline | **+46%** |-| Token savings | Baseline | **+42%** |-| Time savings | Baseline | **+60%** |-| Correctness | 54% | **66% (+12 pts)** |+| Tool calls, 162 runs | baseline | **46% fewer** |+| Uncached input tokens, 162 runs | baseline | **42% fewer** |+| Time, 162 runs | baseline | **60% less** |+| SWE-bench Verified, 50 real issues | 27 solved (54%) | **33 solved (66%)** |++```bash+npm install -g @trailhq/trail-code && trail init+```</div>-<p align="center">- <b>Stop repeating yourself to your coding agent.</b><br/>- You correct it, and by the next session it has forgotten. Trail manages your CLAUDE.md and AGENTS.md so it doesn't.-</p>+> [!NOTE]+> **Graft is now Trail-code.** Graft lives on as the graft map, and every `graft` command still works. What's new is learnings. [What changed](#coming-from-graft)<p align="center">- • Every correction you make becomes a rule your agent keeps.<br/>- • The ones that can't break get a hook that blocks it, not a note it ignores.+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="assets/trail-code-how-it-works-dark.webp">+ <img src="assets/trail-code-how-it-works.webp" alt="Without Trail: each task starts a new session with an agent that has no memory. It searches blind, opens the wrong files, guesses how the code is wired, ships the task, and the context is lost. This repeats for every task and every teammate's agent. With Trail, your agent already knows your code: trail init builds the graft map, a hook points the agent to it before each session, the agent reads the graph with its impact radius, gets precise context, ships the task, then saves learnings. One graph, every agent, up to 4x tokens saved." width="880"/>+ </picture></p>-<p align="center">- <a href="https://app.trailhq.com/get-started?step=repo"><img src="https://img.shields.io/badge/Try%20it%20on%20your%20repo%20%E2%86%92-E5484D?style=for-the-badge" alt="Try it on your repo" height="34"/></a>-</p>+----<p align="center">- <img src="assets/graft-comparison-demo.gif" alt="Side-by-side comparison of a coding agent working with and without graft" width="820"/>-</p>+## What changes in your agent++| Without Trail-code | With Trail-code |+|---|---|+| Greps and opens file after file to find the code it needs | Gets the right files and functions with your prompt |+| Re-explores code a teammate already figured out last week | Starts from their learning: what they decided, what they ruled out, what to watch out for |+| Undoes a teammate's decision, because it never knew about it | `trail check` flags it before the PR, quoting who decided it and why |+| Finds out at merge time that a teammate changed the same file | Opens its reply with the overlap: `● overlap · Kumar's branch kumar/retry also changes client.go` |+| Has to be told the same things every session | Starts from what you've told it before: `trail init` finds what you said more than once in your past sessions |+| You write and update CLAUDE.md by hand | Learnings are saved from your conversations, in files you can read |++**Same model, more tasks solved.** On SWE-bench Verified (real GitHub issues, graded by the maintainers' own tests), Claude Sonnet 5 solved **33 of 50** issues with the graft map and **27 of 50** without it, using 23% fewer tokens. [Details](#swe-bench-verified)++**Cheaper and faster.** Across 162 runs of the same agent on the same tasks: **32% lower cost**, **42% fewer tokens**, **60% less time**, and the same share of correct answers. On popular open-source repos, up to **4× cheaper** and **3× faster**. [Details](#benchmark)---## Contents-- [Trail quick start](#trail-quick-start): learnings your agent leaves for the next session, and your team's+- [How it works](#how-it-works)- [Quick start](#quick-start)-- [The problem](#the-problem)-- [What Graft does](#what-graft-does)-- [Benchmark](#benchmark)-- [SWE-bench Verified](#swe-bench-verified)-- [How the graph gets built](#how-the-graph-gets-built)-- [Supported languages](#supported-languages)-- [What's in a node](#whats-in-a-node)-- [What runs where](#what-runs-where)-- [Agent integration](#agent-integration) — [MCP server](#mcp-server) · [Claude Code (deep integration)](#claude-code-deep-integration)-- [CLI](#cli)-- [Search & orient](#search--orient-graft-grep--graft-map) (`graft grep` / `graft map`)-- [Monorepos & multi-repo folders](#monorepos--multi-repo-folders)-- [Visualize it](#visualize-it-graft-viz) (`graft viz`)-- [Tested on your popular repos](#tested-on-your-popular-repos)-- [Development](#development)-- [License](#license)+- [Part 1: The graft map](#part-1-the-graft-map), your code+- [Part 2: Learnings](#part-2-learnings), what you, your agents and your team know+ - [Four kinds, three places](#four-kinds-three-places) · [One decision, two teammates](#one-decision-two-teammates) · [A learning is a file](#a-learning-is-a-file) · [Your agent does the saving](#your-agent-does-the-saving)+- [Your team](#your-team)+- [What stays on your machine](#what-stays-on-your-machine)+- [Benchmark](#benchmark) · [SWE-bench Verified](#swe-bench-verified) · [Tested on popular repos](#tested-on-popular-repos)+- [FAQ](#faq)+- Reference: [How the graph gets built](#how-the-graph-gets-built) · [Supported languages](#supported-languages) · [What's in a node](#whats-in-a-node) · [What runs where](#what-runs-where) · [Agent integration](#agent-integration) · [CLI](#cli) · [Search & orient](#search--orient-trail-grep--trail-map) · [Monorepos](#monorepos-submodules--multi-repo-folders) · [Visualize it](#visualize-it-trail-viz) · [Development](#development)----## Trail quick start+## How it works-```bash-npm install -g @trailhq/trail-trail init-claude-```+Trail-code has two parts. Both run on your machine.++1. **The graft map: your code.** `trail init` parses your repo with tree-sitter into a map of every file, function and who calls what. No model, no API key. It refreshes itself when the code changes, uncommitted edits included. Your agent gets pointers to the matching files and functions with each prompt, and sees what depends on a file right after it edits it.+2. **Learnings: what you, your agents and your team know.** When a session works something out, or you correct how something is done, your agent saves it as a learning. The next session on that code, yours or a teammate's, starts from it instead of digging again. Learnings about the code are committed with the code; learnings about you stay on your machine. On day one, `trail init` starts you off with what you told Claude more than once in your past sessions.-Install once. `trail init` asks which agents your team uses, builds the code map and wires up Claude Code. Then work the way you always do.+The graft map tells your agent *where* things are. Learnings tell it *why* they are that way, and *how* the work gets done here.-When a session works something out, your agent saves a learning: what it decided, what it ruled out, and what to watch out for. It goes in the repo's `.trail/learnings/`, and you commit it with the change. The next session on that code, yours or a teammate's, gets it back before it starts digging, and ends with a line saying what it saved, like `📝 Started from Anirudh's learning · saved ~27k tokens`. Teammates' Claude reads the learnings even before they install trail, and learnings on a teammate's pushed branch show up before it merges, along with any overlap with your work.+---++## Quick start-Before a PR, `trail check` compares your change with what the team has learned and flags anything that goes against it. It runs on your machine; nothing to sign in to.+```bash+npm install -g @trailhq/trail-code # install the CLI, once+trail init # in your repo: build the graft map, set up .trail/, wire your agents+```-When you want the team's view across repos, your agent offers a link at the end of a reply. Sign in, create a workspace, tick the repos it gets, and invite your team with a link. The team page shows who is learning what, how often learnings are reused, and where work overlaps.+That is the whole setup. `trail init` asks which of your coding agents to wire up, builds the graft map from your code, creates `.trail/` for the repo's learnings, and adds a statusline and hooks to Claude Code. It also reads your past Claude Code sessions in the repo, once, for what you told Claude more than once, and saves those as learnings. Your own Claude Code does that reading, in about a minute. Then work the way you always do. No daemon, no server, nothing to babysit: it is all files.-Trying this branch before `@trailhq/trail` is published:+Commit the setup so your teammates get it too. The graft map itself, in `graft/`, is a local cache like `node_modules` and is added to `.gitignore`, so it stays out of the commit:```bash-git clone -b feat/trail-cloud https://github.com/trailhq/Graft.git trail && cd trail-npm install && npm run build && node scripts/pack-trail.mjs-npm install -g ./build/trail+git add .claude .mcp.json .trail .gitignore .ignore && git commit -m "set up Trail-code"```+Teammates' Claude Code reads the learnings in `.trail/` even before they install anything, and tells them once how to get the rest.++`trail init --dry-run` shows the agent wiring it would write; `trail init --agents claude` wires Claude Code alone.++### Coming from graft?++Nothing breaks. The code map you know is now called the graft map, and it is one of Trail-code's two parts.++| | Before | Now |+|---|---|---|+| Name | graft | Trail-code |+| The code map | graft | the graft map (same thing) |+| Command | `graft` | `trail` (`graft` still works) |+| Package | `@nanonets/graft` | `@trailhq/trail-code` (the old one still works) |+| Learnings | None | New, see [Part 2](#part-2-learnings) |++`graft` and `@nanonets/graft` run the same code as `trail`, and print what they always printed.++Already have graft? `graft upgrade` adds the `trail` command next to it.++Repos that graft set up move to trail on their own: once the `trail` command is installed, each one moves the first time you open Claude Code in it. To move one right away, run `trail init` in it. Commit what changes so your teammates move too.++----## Quick start+## Part 1: The graft map-```bash-npm install -g @nanonets/graft # install the CLI, once-graft init # build the graph + wire it into Claude Code+Without a map, your coding agent starts every task blind. It greps a term, opens a file, follows an import, backs out and tries again, rebuilding a picture of a codebase it mapped an hour ago and threw away. That rediscovery burns most of a run's tool calls, tokens and time. People onboard to a codebase once. Agents onboard every single time.++The graft map builds that understanding once, and keeps it current:++- **Every file, function and caller.** Parsed with tree-sitter into a graph of symbols and who calls what. Deterministic, no model, no network, 23 languages.+- **The right code with every prompt.** In Claude Code, hooks add the matching files and functions to each prompt, and show what depends on a file right after your agent edits it (the "blast radius"). Cursor, Codex and other agents get the same map through MCP tools and their instruction files.+- **Always fresh.** Every query checks the working tree first (a few tens of milliseconds when nothing moved) and rebuilds only what changed, so answers describe the code as it is right now, uncommitted edits included.+- **Plain files you can read.** Linked markdown nodes your agent opens and greps like any other file. No embeddings, no index to keep warm.+- **Summaries if you want them.** `trail build --deep` adds plain-English summaries of each part of the system, written by the model provider you choose, under your own key.++| | Cold Claude Code | Claude Code with the graft map |+|---|---|---|+| SWE-bench Verified, 50 real issues | 27 solved | **33 solved (+12 pts)** |+| Our benchmark, 162 runs | baseline | **32% lower cost, 42% fewer tokens, 60% less time** |+| Popular open-source repos | baseline | **up to 4× cheaper, 3× faster** |++How it is measured: [Benchmark](#benchmark), [SWE-bench Verified](#swe-bench-verified) and [Tested on popular repos](#tested-on-popular-repos). How it is built: [the reference](#how-the-graph-gets-built).++---++## Part 2: Learnings++Your agent forgets everything when a session ends. Next week, it digs through the same code again, or worse, undoes a decision it never knew was made. Your teammates' agents do the same.++Trail-code keeps what your agent works out as **learnings**, saved from your conversations as you work. The next session starts from what you, your agents and your team already know. You don't have to write any of it by hand.++### Four kinds, three places++Every learning has a kind (what it is) and a place (who it is for).++**Three places:**++| Place | What goes there | Where it lives | Who sees it |+|---|---|---|---|+| **Personal** | About you and your machine: your setup, your habits | `~/.trail/` | Only you. Never committed, never uploaded |+| **Repo** | About the code: why it is the way it is, how work gets done in it | the repo's `.trail/`, committed with the change | Everyone who clones the repo, even before they install Trail-code |+| **Team** | What your whole team has learned, across repos | a Trail workspace (soon) | Your team, on the team page |++Your agent picks between personal and repo: something about your own setup stays personal ("saved just for you"); something about the code goes in the repo ("saved for your team"). The team place will gather the repo learnings of every repo in your workspace, so your team sees them together.++**Four kinds:**++| Kind | Example | Personal | Repo | Team |+|---|---|:---:|:---:|:---:|+| **Decisions**: why the code is the way it is | *"Keep retries at 4. Ruled out 10: one call could block for over an hour."* | ✅ | ✅ | soon |+| **Preferences**: how you like things done | *"Use pnpm, not npm."* Saved when you correct your agent, and found in your past sessions by `trail init`. | ✅ | ✅ | soon |+| **Skills**: how a job is done here | *"Read rotation with page.Rotation(), never pdfcpu: it drops /Rotate."* | soon | soon | soon |+| **Guardrails**: what must never happen | *"Never push to main."* Checked before the command runs. | soon | soon | soon |++Decision or preference? Ask whether it points at specific code and goes stale when that code changes. If it does, it is a decision. If not, it is a preference.++### One decision, two teammates++A real test: two people, two clones of [hashicorp/go-retryablehttp](https://github.com/hashicorp/go-retryablehttp), headless Claude Code sessions.++**1. Anirudh works out why the retry count is 4.** Before committing, the agent saves what it found as a learning, and commits it with the change:++```text+✓ saved for your team · .trail/learnings/2026-10-09-keep-the-default-retry-count-at-anirudh.md```-That is the whole setup. `graft init` asks which of your coding agents to wire up, builds `graft/` from your code, and drops a statusline and hooks into `.claude/`, so from the next session on Graft rides along in Claude Code: it pulls the matching nodes into each prompt and rebuilds the graph in the background after every turn. No daemon, no re-indexing to remember, nothing to run or maintain by default — the graph is just files.+The reply ends with `📝 Committed · Kumar works in this part of the codebase, and their agents now get a 27k-token head start`.-Nothing is written until you pick. Run `graft init --dry-run` to see every file it would touch first, or `graft init --agents claude` to skip the prompt and wire Claude Code alone.+**2. Kumar pulls and asks about the same code.** Kumar's Claude reads Anirudh's learning before exploring, answers from it in 11 seconds for $0.10, and ends with a line saying where the answer came from, like:-`graft build` adds `graft/` to your `.gitignore` automatically — the graph is a local, regenerable cache (like `node_modules`), not something you commit. What you share is the wiring `init` dropped into `.claude/`; each teammate runs `graft build` to generate their own graph:+```text+📝 Started from Anirudh's learning · saved ~27k tokens+```-```bash-git add .claude && git commit -m "wire in graft"+**3. Kumar raises the retry count to 10 anyway.** Before the PR, `trail check` compares the change with everything the team has learned:++```text+checking 1 changed file against 1 learning and 0 skills++✗ client.go:51+ changes defaultRetryMax from 4 to 10+ Anirudh · Oct 9: Keep defaultRetryMax = 4: ten retries with the+ default backoff can hold one Do() call for over an hour.++· 1 conflict · fix it, or say why in the commit message or PR description```-Prefer not to install globally? `npx @nanonets/graft init` works the same way.+Kumar's Claude explains the override in the commit.-<p align="center">- <img src="assets/graft-terminal.png" alt="Two commands — npm install and graft init — then Graft rides along in a Claude Code session, statusline synced" width="820"/>-</p>+**4. Anirudh asks about the same code again.** Kumar's branch isn't merged yet, but Anirudh's Claude opens its reply with:+```text+● overlap · Kumar's branch kumar/retry also changes client.go (pushed today 15:32)+```++None of this needs a server. Learnings travel through git, like the code they are about.++### A learning is a file++A decision is a short markdown file in `.trail/learnings/`, reviewed in the pull request like any other change:++```markdown+---+title: Keep the default retry count at 4+author: Anirudh+date: 2026-10-09+cost: { tokens: 27400 }+touches:+ - client.go----## The problem+## Decided+- Keep defaultRetryMax = 4: ten retries with the default backoff can hold one Do() call for over an hour.-Every task, your coding agent starts blind. Before it changes anything, it re-explores the repo: grep a term, open a file, follow an import, back out, try again. It is rebuilding a picture of a codebase it mapped an hour ago and threw away. That rediscovery burns most of a run's tool calls, tokens, and latency, and it is pure overhead:+## Tried and ruled out+- Raising the default to 10 for one customer: worst case, a single Do() call blocks for over an hour.-- **Repeated.** Every task pays the exploration cost again, from zero.-- **Discarded.** Whatever the agent figured out dies with the session.-- **Unshared.** The next teammate, and their agent, start from scratch too.+## Watch out+- RetryWaitMax caps each wait at 30s, not the total: the waits add up with every retry.+```-Humans onboard to a codebase once. Agents onboard every single time.+`touches` is how the next session on `client.go` finds it. A learning also records what the session spent working it out, in minutes and tokens. That is where "saved ~27k tokens" comes from: what the learning took to work out, less what it costs to read.-<p align="center">- <img src="assets/graft-site-act-demo.gif" alt="A no-map agent's exploration trail wandering file to file before it finds what it needs" width="820"/>-</p>+Where everything lives:++```text+your-repo/+├── .trail/learnings/ learnings about this repo's code (commit them)+└── graft/ the graft map, a local cache (gitignored)++~/.trail/ your personal learnings, on this machine only+```++### Your agent does the saving++Your agent saves and uses learnings on its own, at these moments:++- **On day one, what you told Claude before.** `trail init` reads your own messages in the repo's past Claude Code sessions, leaving out tool output, pasted text and headless runs. It keeps only what you said in two or more sessions, and scrubs secrets.+- **After real digging, a decision.** When a turn took real work and nothing was saved yet, Claude Code is asked once a session to save a learning: what was decided, what was ruled out, what to watch out for. A summary, never a transcript, and nothing secret.+- **After a correction, a learning.** When you correct how something is done here, or state a rule for it, your agent saves that too, so nobody has to say it again.+- **Before each task, the learnings on it.** Each session starts with the learnings that apply to all work in the repo. Each prompt brings in the ones earlier sessions left on that code, above the code itself. A teammate's learning says whose it is.+- **Before a PR, the check.** Your agent is told to run `trail check` before it commits, pushes or opens a pull request.+- **Never rewrites history.** Your agent never edits an existing learning. When it goes against one, it says why in the commit and saves a new one.++The commands, if you want them:++```bash+trail note --title "<what it was about>" # save a learning (the text on stdin); --personal keeps it in ~/.trail+trail check # check your branch against everything the team has learned+trail team # what the team learned this week, and where work overlaps+trail status # the graft map, learnings and tokens saved, on one screen+```----## What Graft does+## Your team-Graft builds that understanding **once** and writes it into your repo as a folder of linked markdown files, one node per system, API, or concept.+Learnings reach your teammates through git, with no server: commit `.trail/`, and every clone has them. Learnings on a teammate's pushed branch show up before it merges, marked "pushed and not merged yet", with only their first lines.-- **Real explanations, not a list of symbols.** Each node says, in plain English, what a part of the system does and how it connects to the rest, the way a senior engineer would explain it. That is the part an agent actually needs so it can skip the exploration. It is not a dump of function names.-- **A real graph you can read.** No embeddings, no similarity search, no index to keep warm. The graph is a set of linked files your agent opens, greps, and follows, exactly the way it reads any other file in the repo.-- **A local cache, not a committed artifact.** `graft build` writes `graft/` and adds it to `.gitignore` — it's a regenerable local cache, like `node_modules`. What you commit is the small wiring `graft init` drops in (`.claude/`, `AGENTS.md`, the MCP config); each teammate runs `graft build` to generate their own graph. No database, no server, no setup.-- **Always fresh, automatically.** Every query rebuilds the graph against the working tree first — structural, `$0`, ~3ms when nothing moved — so `ask`/`grep`/`callers`/`skeleton`/`map` describe the code as it is right now, including uncommitted edits. `graft check` is a local freshness signal; there's no stale index to babysit.-- **Your provider, your key, your model.** Summaries are written by any provider you choose — OpenAI, Anthropic (native), OpenRouter, Fireworks, Groq, OrcaRouter, a LiteLLM proxy, or a local model — under your own key. The structural code graph (`graft build`, `graft check`) is deterministic tree-sitter and never calls a model at all.+`trail team` shows the last 7 days in your terminal: what the team learned and where work overlaps.-<p align="center">- <picture>- <source media="(prefers-color-scheme: dark)" srcset="assets/graft-cold-vs-graft-dark.png">- <img src="assets/graft-cold-vs-graft.png" alt="The same task, 'fix the auth bug', run two ways. A cold Claude Code session re-reads the repo and wanders file to file; Claude Code + graft loads its map once and rides the hooks to one clean pass. With Graft: 46% fewer tool calls, 42% fewer tokens, 60% less time, +22% more SWE-bench instances resolved." width="880"/>- </picture>-</p>+```bash+trail team # this week's learnings and overlaps+```++Coming soon: a Trail workspace, for your team's view across repos. A team page will show who is learning what, how often learnings were reused, and where work overlaps.++---++## What stays on your machine++- **Your code.** The graft map is built on your machine with tree-sitter. No model, no network. The optional `trail build --deep` summaries go to the model provider you choose, under your own key.+- **Personal learnings.** Kept in `~/.trail`. Never committed, never uploaded.+- **Repo learnings.** Files in your repo, shared through git like any other file.+- **Your past sessions.** `trail init` reads your own messages from Claude Code's transcripts for the repo, on your machine. Your own Claude Code does the reading, with Claude Sonnet under your login, so your messages go only to Anthropic, and it counts toward your Claude usage. None of it goes to Trail.+- **If you connect a Trail workspace.** No learning goes to Trail until you do. Once connected, the learnings in the repos you picked go to Trail, including those on teammates' pushed branches. So does a record of each search and check that used them: the search text, the files, and whose learnings were shown. That is how the team page counts reuse.+- **Anonymous usage stats.** Buckets and fixed labels only, never the title, text or paths of a learning. [`TELEMETRY.md`](TELEMETRY.md) lists every field. Turn it off with `trail telemetry disable` or `DO_NOT_TRACK=1`.---## Benchmark-An agent that reads the graph should be cheaper and faster without getting more answers wrong. That's the whole claim, so we measured it instead of asserting it.+An agent that reads the graft map should be cheaper and faster without getting more answers wrong. That's the whole claim, so we measured it instead of asserting it.-The harness ran three variants of the same Claude Sonnet 5 agent with the same file tools: **cold** (explores from zero), **Graft** (a `graft ask --source` bundle pushed up front), and **pull** (graft_find_code/graft_file_api tools, nothing injected — context paid for only when asked). An Opus 4.8 judge scored correctness with a required-keyword floor, so a fast-but-wrong answer couldn't win by being fast. Cost is cache-aware: reads ≈0.1×, writes 1.25×, the billing model agents actually run under.+The harness ran three variants of the same agent loop on Claude Sonnet 5, with the same file tools: **cold** (explores from zero), **push** (a `trail ask --source` bundle up front), and **pull** (the `trail_find_code` and `trail_file_api` tools, nothing injected, context paid for only when asked). An Opus 4.8 judge scored correctness with a required-keyword floor, so a fast but wrong answer couldn't win by being fast. Cost is cache-aware: reads ≈0.1×, writes 1.25×, the billing model agents actually run under.-162 runs, two repos (graft itself and a real Node/Express auth service), 3 trials each, tasks split between single-file and multi-file questions.+162 runs, two repos (this one and a real Node/Express auth service), 3 trials each, tasks split between single-file and multi-file questions.-| Metric (mean/task) | Cold Claude Code | Claude Code with graft |+| Metric (mean/task) | Cold agent | Agent with the graft map (push) ||---|---|---|-| Cost savings ($) | 0.0429 | **0.0292 (+32%)** |-| Token savings | 8,070 | **4,650 (+42%)** |-| Tool-call savings | 4.2 | **2.3 (+46%)** |-| Latency savings (s) | 39.8 | **15.8 (+60%)** |+| Cost ($) | 0.0429 | **0.0292 (32% lower)** |+| Uncached input tokens | 8,070 | **4,650 (42% fewer)** |+| Tool calls | 4.2 | **2.3 (46% fewer)** |+| Latency (s) | 39.8 | **15.8 (60% less)** || Correctness | 93% | 93% (equal) |-Graft never answered worse than cold, on any corpus. The pull variant gave up most of that speed for something bigger: correctness jumped to 98%, +5 points over cold, the strongest single result in the sweep. Push when speed is what you need; pull when being right matters more.+Push, the column above, gave up 3 correctness points on one corpus for its savings. The pull variant never answered worse than cold on any corpus, and gave up most of that speed for something bigger: correctness jumped to 98%, 5 points over cold, the strongest single result in the sweep. Push when speed is what you need; pull when being right matters more.---## SWE-bench Verified-The sweep above is our harness measuring our mechanism. So we ran the industry-standard one too — **SWE-bench Verified**, real GitHub issues from real repos, graded by the official `swebench` harness. No judge model, no similarity score: your patch is applied, the maintainers' own tests are run, and you either flip the failing test without breaking the passing ones or you don't.+The sweep above is our harness measuring our mechanism. So we ran the industry-standard one too: **SWE-bench Verified**, real GitHub issues from real repos, graded by the official `swebench` harness. No judge model, no similarity score: your patch is applied, the maintainers' own tests are run, and you either flip the failing test without breaking the passing ones or you don't.-**50 instances**, same model on both arms — **Claude Sonnet 5** — same Docker images, same turn limits. The only difference is whether graft is wired in.+**50 instances**, the same model on both arms (**Claude Sonnet 5**), the same Docker images, the same turn limits. The only difference is whether the graft map is wired in.-| Correctness & efficiency | Cold Claude Code | Claude Code with graft | Improvement |+| Correctness & efficiency | Cold Claude Code | Claude Code with the graft map | Improvement ||---|---|---|---|| Correctness | 27 / 50 (54%) | **33 / 50 (66%)** | **+12 pts** |-| Token savings | 142.0M | **109.4M** | **+23%** |-| Cost savings | $52.34 | **$42.43** | **+19%** |-| Tool-call savings | 1,370 | **1,031** | **+25%** |-| API-request savings | 2,455 | **1,875** | **+24%** |-| Wall-clock savings | 13,094s | **8,922s** | **+32%** |+| Tokens | 142.0M | **109.4M** | **23% fewer** |+| Cost | $52.34 | **$42.43** | **19% lower** |+| Tool calls | 1,370 | **1,031** | **25% fewer** |+| API requests | 2,455 | **1,875** | **24% fewer** |+| Wall-clock | 13,094s | **8,922s** | **32% less** |-graft resolved **33 of 50 instances** against Cold Claude Code's 27 — and got there with 25% fewer tool calls, 23% fewer tokens, and 32% less wall-clock time. Every correctness win has the same shape: the baseline patches one file and misses its siblings. On `django-11532` it patched 1 of the 5 files the fix requires and broke 18 previously-passing tests, twice over. On `django-16263` it patched 1 of 4 and scored 102 / 103. graft found the rest — and on `django-16263` did it in half the tokens and half the time.+The graft map resolved **33 of 50 instances** against cold Claude Code's 27, with 25% fewer tool calls, 23% fewer tokens and 32% less wall-clock time. Every correctness win has the same shape: the baseline patches one file and misses its siblings. On `django-11532` it patched 1 of the 5 files the fix requires and broke 18 previously passing tests, twice over. On `django-16263` it patched 1 of 4 and scored 102 / 103. The graft map found the rest, and on `django-16263` did it in half the tokens and half the time.-Two harnesses, two claims: the controlled sweep says graft is cheaper and faster, SWE-bench says it's also more correct.+Two harnesses, two claims: the controlled sweep says the graft map is cheaper and faster, SWE-bench says it's also more correct.<sub>Correctness over all instances; tokens, cost and calls over the instances both arms resolved, for a like-for-like comparison. Official SWE-bench Verified images and official `swebench` 4.1.0 grader, native x86_64.</sub>---+## Tested on popular repos++The [benchmarks](#benchmark) measure the mechanism. The real test is whether the graft map helps an agent **ship real changes** on code people actually run, not just answer questions. So we benchmark it on popular open-source repos: **15 tasks each**, 10 real developer questions plus **5 actual implementation tasks** (real merged pull requests, each re-implemented from its base commit and scored against the files the maintainers actually changed). Same agent (Claude Opus), same file tools; the only difference is whether the graft map is wired in.++On PocketBase the graft map ran **21% cheaper and 14% faster** across the 15 tasks, and **2.6× cheaper** on the hardest cross-file question, with no loss of correctness: it reproduced the real merged PRs by touching the same files the maintainers did.++### PocketBase (Go, ~350 files)++| Aggregate over 15 tasks | Standard Claude Code | With the graft map |+|---|---|---|+| Cost | $13.91 | **$11.02 (−21%)** |+| Wall-clock | 2,044s | **1,762s (−14%)** |+| PRs reproduced | 5 / 5 | **5 / 5 (same files as the maintainers)** |++Cheaper and faster with no loss of correctness: the graft map reproduced all five merged PRs, touching the same files the maintainers did. The gap is widest on cross-file understanding: "how does auth work across OAuth2 providers" dropped from $2.19 to $0.84.++<details>+<summary><b>The 10 questions we asked</b></summary>++1. **Orientation**: Give me a map of PocketBase's architecture: the main subsystems and how an HTTP request flows through to the database.+2. **Entry-point trace**: Trace end-to-end what happens when a client creates a record via the REST API, from route handler to database write.+3. **Feature location**: I want to add a brand-new collection field type. Where do I hook it in, and which pieces must change?+4. **Bug localization**: Realtime subscriptions silently stop delivering events after a while. Where would you start looking, and why?+5. **Blast radius**: If I change the signature of the record-validation logic, what depends on it and what could break?+6. **Cross-file synthesis**: How does auth work across OAuth2 providers: where are tokens issued, validated, stored, and refreshed?+7. **Extensibility**: How do I use PocketBase as a Go framework to register a custom route plus an on-record-create hook?+8. **Security discovery**: Where is user input validated, and where are collection API access rules enforced before a query runs?+9. **Public API**: As an external app, how do I authenticate and then list and filter records over the REST API?+10. **Test verification**: Where are the tests for the record CRUD API, and what do they assert about access rules?++</details>++<details>+<summary><b>The 5 merged PRs we re-implemented</b></summary>++Each PR was reset to its base commit; the agent's diff was scored against the files the merged PR changed.++| PR | Type | What it does | Files the maintainers touched |+|---|---|---|---|+| [#6744](https://github.com/pocketbase/pocketbase/pull/6744) | feat | Generate & serve WebP thumbnails | `apis/file.go`, `tools/filesystem/filesystem.go` |+| [#6947](https://github.com/pocketbase/pocketbase/pull/6947) | fix | Uniform char distribution in regex random strings | `tools/security/random_by_regex.go` |+| [#6690](https://github.com/pocketbase/pocketbase/pull/6690) | refactor | Patreon OAuth2 to use `x/oauth2/endpoints` | `tools/auth/patreon.go` |+| [#2726](https://github.com/pocketbase/pocketbase/pull/2726) | perf | Drop a redundant admin-count query on a hot middleware path | `apis/middlewares.go` |+| [#3192](https://github.com/pocketbase/pocketbase/pull/3192) | fix | Restore prior API rules on automigration rollback | `plugins/migratecmd/templates.go` |++</details>++<details>+<summary><b>Method</b></summary>++Two clones of PocketBase at the same commit: one wired with `graft init`, one untouched and verified to have no graft map in it. Each task run headless (`claude -p`, Claude Opus) with an empty MCP config. Understanding questions were graded by whether the answer pointed to the right files and functions; PR tasks were scored on whether the agent's diff touched the same files as the merged PR. Every transcript was audited to confirm the graft map was actually used in one arm and absent from the other.++</details>++---++## FAQ++**Is this graft?**+Yes. Trail-code is graft's new name, and graft lives on inside it as the graft map. The command is `trail` and the package is `@trailhq/trail-code`; `graft` and `@nanonets/graft` run the same code, print what they always printed, and keep working.++**How is this different from CLAUDE.md or AGENTS.md?**+You write those by hand, keep them current by hand, and your agent can skip them. Trail-code saves learnings from your conversations, brings in only the ones about the code you're working on, checks your changes against them before a PR, and adds a map of your code. It works next to your instruction files: `trail init` never touches your `CLAUDE.md`.++**Will it fill up my context window?**+No. Each prompt gets only pointers to the matching code, and the learnings that match it, and a teammate's unmerged learnings show only their first lines. In our benchmark, uncached input tokens went down 42%.++**Do I need an API key?**+No. The graft map, the hooks, learnings and `trail check` all work without one. A key only adds the written summaries from `trail build --deep`.++**Do I need to sign in?**+No. Everything above works on your machine, and learnings reach your team through git. A Trail workspace, coming soon, is only for the team page across repos.++**Which agents does it work with?**+Claude Code gets the deepest setup: hooks, statusline, learnings with every prompt, and the ask to save one after real digging. Trail-code also wires Cursor, Codex and other `AGENTS.md` readers, Gemini CLI, GitHub Copilot, Windsurf, Kiro, Antigravity, Grok, Hermes and AdaL, and serves any agent that speaks MCP.++**What if it learns something wrong?**+A repo learning is a file in your pull request, so it gets reviewed like the code it is about. Delete or edit the file to drop it. Personal learnings are files in `~/.trail`, just as easy to change.++**Does it work in monorepos?**+Yes: one repo with many packages, submodules, and folders of separate repos. See [Monorepos](#monorepos-submodules--multi-repo-folders).++**What does it cost?**+The CLI is free and open source under the MIT license.++---+## How the graph gets built-Graft builds the graph in two passes, both powered by a language model:+The graft map is built in layers. Tier 1 is tree-sitter: every symbol and call edge, no model, no key. `trail build --deep` adds two language-model passes on top:1. **Read each file.** Every source file is summarized once into a short description of what it does.-2. **Group into nodes.** Those summaries are grouped into a curated set of nodes (subsystems, key files, and concepts) with typed links between them. Graft chooses the right level of detail for you instead of making one node per file, so a big repo becomes a few dozen readable nodes.+2. **Group into nodes.** Those summaries are grouped into a curated set of nodes (subsystems, key files, and concepts) with typed links between them. The graft map chooses the right level of detail for you instead of making one node per file, so a big repo becomes a few dozen readable nodes.```mermaidflowchart LR- S[Source files] --> T["Tier 1 — tree-sitter<br/>no model, no key"]- S --> P1["Pass 1 — LLM summarizes<br/>each file (--deep)"]+ S[Source files] --> T["Tier 1: tree-sitter<br/>no model, no key"]+ S --> P1["Pass 1: LLM summarizes<br/>each file (--deep)"]T --> W["graft/.graph/wiring.json<br/>per-symbol code graph"]- P1 --> P2["Pass 2 — group into nodes<br/>+ typed links"]+ P1 --> P2["Pass 2: group into nodes<br/>+ typed links"]P2 --> N["graft/*.md<br/>markdown node graph"]```-Every pass is cached by content hash — the LLM ones and the tree-sitter parse alike. Re-running only touches the files that changed, so the second build is fast and cheap (on this repo, 124 files: 0.74s cold, 0.18s after one edited file, 0.18s with nothing changed). `graft build --no-reuse` forces a cold re-parse.+Every pass is cached by content hash, the LLM ones and the tree-sitter parse alike. Re-running only touches the files that changed, so the second build is fast and cheap (on this repo, 312 files: about 5s cold, about 0.6s after one edited file or with nothing changed). `trail build --no-reuse` forces a cold re-parse.-That cheapness is what lets **every query refresh the graph before it answers**. A retrieval call stats the tree against the last build's fingerprint (~3ms), and rebuilds only if something moved — so `ask`/`grep`/`callers`/`skeleton`/`map` describe the code as it is right now, including edits that are unsaved to git: uncommitted, unstaged, or staged all look the same to graft. Git determines the visible file set; freshness compares the working-tree bytes rather than commit or index state. The refresh is structural and `$0`; it never calls the LLM. Turn it off per-command with `--no-refresh`, or everywhere with `GRAFT_NO_REFRESH=1`.+That cheapness is what lets **every query refresh the graph before it answers**. A retrieval call stats the tree against the last build's fingerprint (about 50ms on this repo), and rebuilds only if something moved, so `ask`/`grep`/`callers`/`skeleton`/`map` describe the code as it is right now, including edits that are unsaved to git: uncommitted, unstaged, or staged all look the same to the graft map. Git determines the visible file set; freshness compares the working-tree bytes rather than commit or index state. The refresh is structural and `$0`; it never calls the LLM. Turn it off per-command with `--no-refresh`, or everywhere with `GRAFT_NO_REFRESH=1`.-Alongside the markdown graph, `graft build` builds `graft/.graph/wiring.json` — a per-symbol code graph — plus a per-file wiring card mirroring your source tree. Tier 1 is pure tree-sitter (every function, class, and call edge; deterministic, no model, no network), which is why plain `graft build` needs no key. The `--deep` pass adds a one-line summary and a crux excerpt per symbol, cached by body hash.+Alongside the markdown graph, `trail build` builds `graft/.graph/wiring.json` (a per-symbol code graph) plus a per-file wiring card mirroring your source tree. Tier 1 is pure tree-sitter (every function, class, and call edge; deterministic, no model, no network), which is why plain `trail build` needs no key. The `--deep` pass adds a one-line summary and a crux excerpt per symbol, cached by body hash.---## Supported languages-Graft parses with tree-sitter at two levels of fidelity, plus an optional-compiler-grade layer — all `$0` and deterministic (no model, no key):+The graft map parses with tree-sitter at two levels of fidelity, plus an optional+compiler-grade layer, all `$0` and deterministic (no model, no key):-- **Full-fidelity** — hand-written extractors with scope-aware, cross-file call+- **Full-fidelity**: hand-written extractors with scope-aware, cross-file calland import resolution:**TypeScript / JavaScript** (incl. JSX & TSX), **Python**, **Go**, **Java**,**Kotlin**, **PHP**, **Swift** (classes, structs, enums, actors, protocols;- extension members attach to the extended type), **R** (`.R`/`.r` — plain+ extension members attach to the extended type), **R** (`.R`/`.r`: plainfunctions, S3/S4/R6 classes and methods, roxygen `@export`,- `library()`/`source()` imports).+ `library()`/`source()` imports), and **Vue** single-file components (their+ `<script>` blocks go through the TypeScript extractor).-- **Broad** — symbols (functions, classes, methods, types, …) plus name-resolved+- **Broad**: symbols (functions, classes, methods, types, …) plus name-resolvedcall edges via a generic tree-sitter extractor, one grammar per language:**Rust, C, C++, C#, Ruby, Scala, Elixir, Solidity,- OCaml, Zig, Dart, Clojure, Nix, Lua**.+ Dart, Clojure, Nix, Lua**, and **OCaml, Zig** (symbols only for now, no call edges).-- **Compiler-grade edges (opt-in)** — `graft build --lsp` adds precise+- **Compiler-grade edges (opt-in)**: `trail build --lsp` adds precise`lsp_resolved` call edges (member calls the static pass can't type) when a- language server is on your `PATH`: **rust-analyzer** (Rust), **clangd** (C/C++),+ language server is on your `PATH`. It uses the first one installed, in this+ order, one server per build: **rust-analyzer** (Rust), **clangd** (C/C++),**gopls** (Go), **pyright** (Python), **typescript-language-server** (TS/JS).- It's best-effort — with no server installed the graph is unchanged.+ It's best-effort: with no server installed the graph is unchanged.-Twenty-three languages in total. A file whose language isn't listed is skipped, not-indexed. Adding a broad-tier language is a small contribution — see+Twenty-three languages, plus Vue single-file components. A file whose language isn't listed is skipped, not+indexed. Adding a broad-tier language is a small contribution; see[CREDITS.md](CREDITS.md) for the folks who added the current set.---## What's in a node-A node is a single markdown file. Most code maps stop at an address: this thing lives in that file, on that line. That tells an agent where to look, not what it will find, so it still has to open the source and read. A Graft node holds the meaning inline, so the agent learns what it needs up front and opens the file only when it wants more.+A node is a single markdown file. Most code maps stop at an address: this thing lives in that file, on that line. That tells an agent where to look, not what it will find, so it still has to open the source and read. A graft map node holds the meaning inline, so the agent learns what it needs up front and opens the file only when it wants more.Each node holds:@@ -270,194 +513,210 @@ Each node holds:|---|---|| **Summary** | A plain-English explanation of what the code does, written by the model and cached. It is there whether or not the code was ever documented, and it is regenerated when the source changes. || **Crux** | The handful of lines that actually carry the logic: the guard, the skip condition, the state change. Lifted straight from the source and stored inline, so the agent sees *how* it works, not just what. |-| **Sources** | The exact files the node is built from, each tracked by a content hash, so Graft can tell precisely when a node has gone stale. |+| **Sources** | The exact files the node is built from, each tracked by a content hash, so the graft map can tell precisely when a node has gone stale. || **Links** | Typed connections to other nodes (`depends_on`, `part_of`, `uses`, `implements`, `produces`), written as `[[wikilinks]]` your agent can follow. |-| **Notes** | Anything you write below the generated block. It is preserved across regenerations, so your own context is never overwritten. |+| **Your text** | Anything you write below the generated block. It is preserved across regenerations, so your own context is never overwritten. |-That is three depths in one file: the summary says *what* the code does, the crux shows *how*, and the sources point to the rest if the agent needs it. A plain index makes it read a whole file to learn one thing. A Graft node hands it the answer inline, and the follow-up read often never happens.+That is three depths in one file: the summary says *what* the code does, the crux shows *how*, and the sources point to the rest if the agent needs it. A plain index makes it read a whole file to learn one thing. A graft map node hands it the answer inline, and the follow-up read often never happens.The crux is stored as the code itself, not as a line range, on purpose. Line numbers drift whenever unrelated code above them shifts, but the lines that matter do not. Keeping the text, not the numbers, means the crux stays correct even as the file around it moves.-_Summary, sources, links, and notes ship today in markdown nodes. The crux ships per-symbol in the code graph (`graft build --deep`); inlining it into markdown nodes is next._+_Summary, sources, links, and your text ship today in markdown nodes. The crux ships per-symbol in the code graph (`trail build --deep`); inlining it into markdown nodes is next._---## What runs where-- **On your machine, no key, no network:** the structural code graph. `graft build` (wiring graph + per-file cards), `graft check`, and `graft ask` are deterministic tree-sitter — they never call a model.-- **Through your provider key:** the LLM-written parts — `graft build --deep` adds the concept nodes (file summaries + node synthesis) and the per-symbol summaries and cruxes. graft is vendor-neutral: set `GRAFT_PROVIDER` (`openai` for any OpenAI-compatible endpoint, `anthropic` for the native API, or `litellm` / `orcarouter` for a gateway that speaks the OpenAI-compatible format), your `GRAFT_API_KEY`, `GRAFT_MODEL`, and — for the `openai` wire format — `GRAFT_BASE_URL` to point at OpenRouter, Fireworks, Groq, a LiteLLM proxy, a local server, or OpenAI itself. Or pass `--provider/--model/--api-key/--base-url` on the command line. (`OPENROUTER_API_KEY` still works as a deprecated fallback, and `ORCAROUTER_API_KEY` as a second one.)-- **Anonymous usage stats** — the only network calls are the LLM requests you configured, a daily npm version check, and one batched usage ping. The ping carries buckets and fixed labels only: never your code, file paths, repo name, symbols, queries, or error messages. [`TELEMETRY.md`](TELEMETRY.md) is the complete list and `graft telemetry debug` prints exactly what your machine would send. Turn it off with `graft telemetry disable`, `DO_NOT_TRACK=1`, or by unchecking the box in `graft init`; it is off in CI and in any build from source.+- **On your machine, no key, no network:** the structural code graph. `trail build` (wiring graph + per-file cards), `trail build --check`, `trail ask`, learnings and `trail check` are deterministic. They never call a model.+- **Through your provider key:** the LLM-written parts. `trail build --deep` adds the concept nodes (file summaries + node synthesis) and the per-symbol summaries and cruxes. The graft map is vendor-neutral: set `GRAFT_PROVIDER` (`openai` for any OpenAI-compatible endpoint, `anthropic` for the native API, or `litellm` / `orcarouter` for a gateway that speaks the OpenAI-compatible format), your `GRAFT_API_KEY`, `GRAFT_MODEL`, and, for the `openai` wire format, `GRAFT_BASE_URL` to point at OpenRouter, Fireworks, Groq, a LiteLLM proxy, a local server, or OpenAI itself. Or pass `--provider/--model/--api-key/--base-url` on the command line. (`OPENROUTER_API_KEY` still works as a deprecated fallback, and `ORCAROUTER_API_KEY` as a second one.)+- **Through Trail, only if you connect a workspace:** the learnings in the repos you picked, and the searches and checks that used them. See [What stays on your machine](#what-stays-on-your-machine).+- **Anonymous usage stats:** a daily npm version check and one batched usage ping. The ping carries buckets and fixed labels only: never your code, file paths, repo name, symbols, queries, learnings or error messages. [`TELEMETRY.md`](TELEMETRY.md) is the complete list and `trail telemetry debug` prints exactly what your machine would send. Turn it off with `trail telemetry disable`, `DO_NOT_TRACK=1`, or by unchecking the box in `trail init`; it is off in CI and in any build from source.-See [`.env.example`](.env.example) for the full list of settings (model, base URL, graph directory).+Settings keep their `GRAFT_` names. See [`.env.example`](.env.example) for the full list (model, base URL, graph directory).---## Agent integration-One command wires Graft into the coding agents you use:+One command wires Trail-code into the coding agents you use:```bash-npx @nanonets/graft init+npm install -g @trailhq/trail-code && trail init# detects your agents and writes each one's native instruction file;# Claude Code additionally gets the live statusline + hooks below```-On a terminal, `init` shows you every agent it knows about — flagging the ones it detected (via their config directories) and listing the exact files each would write — and wires only the ones you select. Claude Code is pre-selected; nothing else is. Selected agents get a marker-fenced Graft section in their shared instruction file — `AGENTS.md` (Codex, OpenCode and other CLIs that read it), `GEMINI.md`, `.github/copilot-instructions.md` — or a wholly-owned rule/skill file for the agents that use one: `.claude/skills/graft/SKILL.md`, `.cursor/rules/graft.mdc`, `.kiro/steering/graft.md`, `.windsurf/rules/graft.md`, `.grok/skills/graft/SKILL.md` for Grok (xAI), `.adal/skills/graft/SKILL.md` for [AdaL](https://adal.sylph.ai). Claude Code is in the second group: `init` writes its own skill file and never touches your `CLAUDE.md`. Re-running only updates Graft's own section (or replaces the owned file) and never touches the rest of your content.+On a terminal, `init` shows you every agent it knows about, flags the ones it detected (via their config directories), lists the exact files each would write, and wires only the ones you select. Claude Code is pre-selected; nothing else is. Selected agents get a marker-fenced Trail-code section in their shared instruction file (`AGENTS.md` for Codex, OpenCode and other CLIs that read it, `GEMINI.md`, `.github/copilot-instructions.md`), or a wholly-owned rule or skill file for the agents that use one, such as `.claude/skills/trail/SKILL.md` and `.cursor/rules/trail.mdc`. Claude Code is in the second group: `init` writes its own skill file and never touches your `CLAUDE.md`. Re-running only updates Trail-code's own section (or replaces the owned file) and never touches the rest of your content.-With no TTY to prompt on — CI, a Dockerfile, a piped shell — `init` writes **nothing** and prints the command to run instead. Pass `--agents <ids>` or `--yes` to make a scripted run explicit.+In Claude Code, the committed skill file is also how a teammate without Trail-code installed gets your learnings: it tells their agent where `.trail/learnings/` is, to read it before exploring, and to tell them once how to install the rest.++With no TTY to prompt on (CI, a Dockerfile, a piped shell), `init` writes **nothing** and prints the command to run instead. Pass `--agents <ids>` or `--yes` to make a scripted run explicit.| Flag | Effect ||---|---|-| `--agents <ids...>` | wire only these, no prompt — ids: `agents`, `cursor`, `gemini`, `grok`, `copilot`, `kiro`, `windsurf`, `adal`, `claude` |+| `--agents <ids...>` | wire only these, no prompt; ids: `agents`, `adal`, `cursor`, `gemini`, `grok`, `hermes`, `antigravity`, `copilot`, `kiro`, `windsurf`, `claude` || `--yes`, `-y` | skip the prompt and wire every **detected** agent |-| `--dry-run` | print every file `init` would touch, then exit without writing |+| `--dry-run` | print the agent wiring `init` would write, then exit without writing || `--all-agents` | write instruction files for every known agent, detected or not || `--no-agents` | Claude Code wiring only; skip other agents || `--list-agents` | print the known agent ids and exit |-| `--no-mcp` | skip MCP server registration |-| `--no-hooks` | skip hook installation |+| `--no-mcp` | skip MCP registration for agents other than Claude Code |+| `--no-hooks` | skip hook installation for agents other than Claude Code || `--no-statusline` | skip writing Claude Code `statusLine` (same as `GRAFT_NO_STATUSLINE=1`) || `--no-global` | skip writes outside this repo (the `~/.codex/` entries below) |#### Writes outside the repo-Selecting the `agents` host also touches your **user-level** Codex config, when `~/.codex/` exists:+Some agents also get **user-level** files, so the wiring follows you into worktrees and folders the repo's files don't reach:-| Path | What changes |-|---|---|-| `~/.codex/config.toml` | registers the Graft MCP server (`[mcp_servers.graft]`) |-| `~/.codex/hooks/graft/graft-hooks.cjs` | the post-edit hook shim |-| `~/.codex/hooks.json` | a `PostToolUse` entry matching `Write\|Edit\|MultiEdit` |+| Agent | Path | What changes |+|---|---|---|+| Claude Code | `~/.claude/settings.json` | `SessionStart`, `UserPromptSubmit`, `PostToolUse` and `Stop` hooks |+| Claude Code | `~/.claude/helpers/graft-hooks.cjs` | the hooks shim they call |+| Claude Code | `~/.claude.json` | the `trail` MCP server |+| Codex (`agents`), when `~/.codex/` exists | `~/.codex/config.toml` | the `trail` MCP server |+| Codex | `~/.codex/hooks.json` | the same four hook events, matching `apply_patch\|Write\|Edit\|MultiEdit` after edits |+| Codex | `~/.codex/hooks/graft/graft-hooks.cjs` | the hooks shim |+| Antigravity | `~/.gemini/config/mcp_config.json` | the `trail` MCP server |+| Antigravity | `~/.gemini/skills/trail/SKILL.md` | its skill file |-Both configs are user-level, so they apply to **every** repo you open with Codex, not just this one. The picker labels these `machine-wide`, `--dry-run` lists them in their own section, and `--no-global` skips them while still wiring `AGENTS.md`.+These apply to **every** repo you open with that agent, not just this one. The picker labels them `machine-wide`, `--dry-run` lists them in their own section, and `--no-global` skips them all while still wiring the repo's own files.### MCP server-`graft init` also registers Graft's MCP server with agents that support it, so these six tools appear natively, no shell required. Claude Code gets this too: `graft init` writes the server into the project's `.mcp.json` (restart Claude Code to load it). Skip with `--no-mcp`; run it manually with `graft mcp [dir]`.+`trail init` also registers the Trail-code MCP server with agents that support it, so these six tools appear natively, no shell required. Claude Code gets this too: `trail init` writes the server into the project's `.mcp.json` (restart Claude Code to load it). Run it by hand with `trail mcp [dir]`.| Tool | Takes | What it's for ||---|---|---|-| `graft_find_code` | a question | Ranked nodes with file:line, source inlined — usually the full answer, no follow-up read needed. |-| `graft_file_api` | a file path | Every signature in that file, no bodies — the API surface for a tenth of the tokens. |-| `graft_trace_calls` | a symbol | Who depends on it, or what it depends on with `direction: out`, N levels deep for blast radius. |-| `graft_find_all` | a regex | Every hit, grouped by enclosing symbol, ranked by how coupled that symbol is. |-| `graft_repo_map` | nothing | A first look at an unfamiliar repo: directory clusters, hubs, hotspots. |-| `graft_check_freshness` | nothing | Whether the local graph has drifted from the code. |+| `trail_find_code` | a question | Ranked nodes with file:line, source inlined; usually the full answer, no follow-up read needed. |+| `trail_file_api` | a file path | Every signature in that file, no bodies: the API surface for a tenth of the tokens. |+| `trail_trace_calls` | a symbol | Who depends on it, or what it depends on with `direction: out`, N levels deep for blast radius. |+| `trail_find_all` | a regex | Every hit, grouped by enclosing symbol, ranked by how coupled that symbol is. |+| `trail_repo_map` | nothing | A first look at an unfamiliar repo: directory clusters, hubs, hotspots. |+| `trail_check_freshness` | nothing | Whether the local graph has drifted from the code. |-Register it by hand if your agent needs it explicit:+The same server still answers the old `graft_*` tool names. Register it by hand if your agent needs it explicit:```json-{ "mcpServers": { "graft": { "command": "npx", "args": ["-y", "@nanonets/graft", "mcp"] } } }+{ "mcpServers": { "trail": { "command": "npx", "args": ["-y", "@trailhq/trail-code", "mcp"] } } }```-Where a CLI agent supports user-level `hooks.json`, `init` also installs Graft's post-edit hook — blast-radius warnings and automatic `$0` graph re-sync after edits (skip with `--no-hooks`).+Where a CLI agent supports user-level `hooks.json`, as Codex does, `init` also installs Trail-code's hooks there: session start, context with each prompt, blast radius and a `$0` graph re-sync after edits, and the end-of-turn sync (skip with `--no-hooks`).### Claude Code (deep integration)-`graft init` always wires up Claude Code, and Claude Code gets more than the skill file above. From then on, any Claude Code session opened in the repo gets:+When Claude Code is selected (it is by default), it gets more than the skill file above. From then on, any Claude Code session opened in the repo gets:-- **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 live statusline**: the graft map's size, how many learnings the repo has, and a `⚠ N stale` warning when the code has moved ahead of the map+- **auto-sync**: every 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 in the matching nodes and the learnings left on that code; editing a file surfaces what depends on it ("blast radius"); new sessions start with the repo map and how many learnings there are+- **the ask to save a learning**: after a turn of real digging with nothing saved, Claude is asked once a session to save one+- **overlap with teammates**: at session start, and every few minutes, it reads which files teammates' recent pushed branches change; when one changes the code your prompt is about, Claude says so first<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"/>- <br/><sub>install → init → hooks keep the graph fresh every session</sub>+ <img src="assets/graft-hook-blast-radius-demo.gif" alt="The post-edit hook: editing node-file.ts prints its blast radius (who depends on it) inline, the statusline flips stale → syncing → synced on its own, and the same dependents light up in the viewer" width="820"/>+ <br/><sub>edit a file → blast radius appears inline → graph auto-resyncs → confirmed in the viewer</sub></p>-<p align="center">- <img src="assets/graft-hook-blast-radius-demo.gif" alt="graft's post-edit hook: editing node-file.ts prints its blast radius (who depends on it) inline, the statusline flips stale → syncing → synced on its own, and the same dependents light up in graft viz" width="820"/>- <br/><sub>edit a file → blast radius appears inline → graph auto-resyncs → confirmed in <code>graft viz</code></sub>-</p>--`graft init` is idempotent and never clobbers your existing `.claude/settings.json` — it merges its blocks and leaves the rest alone. A `statusLine` that is not Graft's (anything whose command does not name `graft-statusline.cjs`) is left untouched; re-running `init` will refresh Graft's own helper command if it is already installed. Pass `--no-statusline` (or `GRAFT_NO_STATUSLINE=1`) to skip installing one at all — a project-level `statusLine` would otherwise hide a custom one in `~/.claude/settings.json`. Want the LLM summaries too? Run `graft build --deep` (with a key) whenever you like; auto-sync will never do it for you.+`trail init` is idempotent and never clobbers your existing `.claude/settings.json`: it merges its blocks and leaves the rest alone. A `statusLine` that is not Trail-code's is left untouched; re-running `init` refreshes Trail-code's own helper command if it is already installed. Pass `--no-statusline` (or `GRAFT_NO_STATUSLINE=1`) to skip installing one at all, since a project-level `statusLine` would otherwise hide a custom one in `~/.claude/settings.json`. Want the LLM summaries too? Run `trail build --deep` (with a key) whenever you like; auto-sync will never do it for you.---## CLI+`trail --help` lists the commands in four groups. Every `graft` command still works too.+```bash-graft build [dir] # build graft/ from the code at [dir]: wiring graph + per-file cards (no LLM, no key)-graft build --deep # add the LLM layer: concept nodes + per-symbol summary/crux (cached)-graft build --extensions .ts .py # only include these code extensions-graft build --no-reuse # re-parse every file instead of replaying unchanged ones from cache-graft build --follow-submodules # include initialized submodules; persist the choice for builds + MCP refresh-graft build --no-follow-submodules # exclude submodules again and persist that choice (the default)-graft build --follow-nested-repos # include nested git clones the index doesn't track; persist the choice-graft build --no-follow-nested-repos # exclude nested clones again and persist that choice (the default)--graft ask "<task>" [dir] # query the graph — ranked nodes + exact file:line (no LLM, no key)-graft ask "<task>" --json # machine-readable result-graft ask "<task>" --in <scope> # narrow to one sub-project of a monorepo/multi-repo folder (see below)--graft skeleton <file> [dir] # every signature in one file, no bodies — the API surface for ~1/10th the tokens (no LLM, no key)--graft callers <symbol> [dir] # who calls/references/imports/implements/extends a symbol (no LLM, no key)-graft callers <symbol> --direction out # the reverse: what the symbol itself calls/references (was `graft callees`)-graft callers <symbol> -d N # walk transitively out to depth N — full blast radius (was `graft impact`)--graft grep "<regex>" [dir] # exhaustive regex search over indexed files, grouped by enclosing symbol (no LLM, no key)-graft grep "<regex>" --in <path> # narrow to files at or under this path prefix-graft grep "<regex>" -i --fixed # case-insensitive; treat the pattern as a literal string, not a regex--graft map [dir] # token-budgeted repo orientation — dir clusters, hubs, hotspots (no LLM, no key)-graft map --max-dirs N # raise/lower the number of directories shown--graft blast [dir] # blast radius of a diff: what depends on the lines this change touched (no LLM, no key)-graft blast --base origin/main # diff against the merge base with HEAD — what a PR job runs-graft blast --format markdown # a PR comment: the areas a change can reach, per-symbol detail collapsed under it-graft blast --base origin/main --name # name those areas with one cached LLM call, instead of a full --deep build-graft blast --export-viz site/ # also write the interactive page for this radius (what a PR comment links to)-graft blast --no-owners # skip "who to tag" — by default git history names the people behind each area-graft blast --depth all --format json # the full transitive closure, machine-readable--graft check [dir] # fail (exit 1) if graft/ has drifted from the code (never auto-refreshes — it's the drift report)-graft check --json # print the drift report as JSON+# find code · your agent runs these+trail ask "<task>" [dir] # the matching code and learnings: ranked nodes + exact file:line (no LLM, no key)+trail ask "<task>" --json # machine-readable result+trail ask "<task>" --in <scope> # narrow to one sub-project of a monorepo/multi-repo folder (see below)++trail grep "<regex>" [dir] # exhaustive regex search over indexed files, grouped by enclosing symbol (no LLM, no key)+trail grep "<regex>" --in <path> # narrow to files at or under this path prefix+trail grep "<regex>" -i --fixed # case-insensitive; treat the pattern as a literal string, not a regex++trail skeleton <file> [dir] # every signature in one file, no bodies: the API surface for ~1/10th the tokens (no LLM, no key)++trail callers <symbol> [dir] # who calls/references/imports/implements/extends a symbol (no LLM, no key)+trail callers <symbol> --direction out # the reverse: what the symbol itself calls/references+trail callers <symbol> -d N # walk transitively out to depth N: full blast radius++trail map [dir] # token-budgeted repo orientation: dir clusters, hubs, hotspots (no LLM, no key)+trail map --max-dirs N # raise/lower the number of directories shown# ask / skeleton / callers / grep / map / blast all refresh the graph first if the working tree moved:# --no-refresh # answer from the graph exactly as it is on disk# GRAFT_NO_REFRESH=1 # same, for every command# GRAFT_REFRESH=hash # hash every file instead of trusting size+mtime-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--graft init [dir] # pick which agents to wire (prompts on a terminal; writes nothing until you choose)-graft init --dry-run # list every file it would touch, then exit-graft init --agents cursor kiro # wire only these agents, no prompt (ids: agents, cursor, gemini, grok, copilot, kiro, windsurf, adal, claude)-graft init --yes # no prompt; wire every detected agent-graft init --no-global # skip writes outside this repo (~/.codex/ config + hooks)-graft init --no-statusline # skip Claude Code statusLine (same as GRAFT_NO_STATUSLINE=1)-graft init --no-build # wire the files only; don't build the graph-graft init --all-agents # wire every known agent, detected or not-graft init --list-agents # list known agent ids and exit--graft uninstall [dir] # remove every file and config entry graft wrote here (the inverse of init)-graft uninstall -y # actually remove (without -y it prints what it would remove and exits)-graft uninstall --keep-cache # wiring only; leave graft/ and the .gitignore entry-graft uninstall --no-global # leave out-of-repo files alone (~/.codex, ~/.gemini)--graft version # print the installed + latest published npm version-graft upgrade # npm install -g the latest published version+# team memory+trail note --title "<about>" [dir] # save a decision: what this session decided, tried and ruled out (the text on stdin)+trail note --personal # about your own setup, not the code: keep it in ~/.trail, out of the repo+trail check [dir] # check your branch's diff against the repo's learnings, yours and your skills (exit 1 on a conflict)+trail check --base origin/main # compare against this base instead of origin's default branch+trail team [dir] # what the team learned this week, who's working on what, and where work overlaps++# setup+trail init [dir] # pick which agents to wire (prompts on a terminal; writes nothing until you choose)+trail init --dry-run # list the agent wiring it would write, then exit+trail init --agents cursor kiro # wire only these agents, no prompt (ids: agents, adal, cursor, gemini, grok, hermes, antigravity, copilot, kiro, windsurf, claude)+trail init --yes # no prompt; wire every detected agent+trail init --no-global # skip writes outside this repo (~/.claude, ~/.claude.json, ~/.codex, ~/.gemini)+trail init --no-statusline # skip Claude Code statusLine (same as GRAFT_NO_STATUSLINE=1)+trail init --no-build # wire the files only; don't build the graph+trail init --all-agents # wire every known agent, detected or not+trail init --list-agents # list known agent ids and exit++trail build [dir] # build the graft map in graft/: wiring graph + per-file cards (no LLM, no key)+trail build --deep # add the LLM layer: concept nodes + per-symbol summary/crux (cached)+trail build --check # build nothing: fail (exit 1) if graft/ has drifted from the code, for CI+trail build --deep -e .ts .py # with --deep: only summarize these extensions+trail build --no-reuse # re-parse every file instead of replaying unchanged ones from cache+trail build --follow-submodules # include initialized submodules; persist the choice for builds + MCP refresh+trail build --no-follow-submodules # exclude submodules again and persist that choice (the default)+trail build --follow-nested-repos # include nested git clones the index doesn't track; persist the choice+trail build --no-follow-nested-repos # exclude nested clones again and persist that choice (the default)++trail status [dir] # the graft map, learnings and tokens saved, on one screen+trail upgrade # npm install -g the latest published version# a new version is announced automatically (checked once a day);# after upgrading, the next session refreshes this repo's wiring itself+trail uninstall [dir] # remove every file and config entry it wrote here (the inverse of init)+trail uninstall -y # actually remove (without -y it prints what it would remove and exits)+trail uninstall --keep-cache # wiring only; leave graft/ and the .gitignore entry+trail uninstall --no-global # leave out-of-repo files alone (~/.claude, ~/.claude.json, ~/.codex, ~/.gemini)+trail telemetry [status|enable|disable|debug] # anonymous usage stats; debug prints exactly what would be sent++# CI+trail blast [dir] # blast radius of a diff: what depends on the lines this change touched (no LLM, no key)+trail blast --base origin/main # diff against the merge base with HEAD (what a PR job runs)+trail blast --format markdown # a PR comment: the areas a change can reach, per-symbol detail collapsed under it+trail blast --base origin/main --name # name those areas with one cached LLM call, instead of a full --deep build+trail blast --export-viz site/ # also write the interactive page for this radius (what a PR comment links to)+trail blast --no-owners # skip "who to tag" (by default, git history names the people behind each area)+trail blast --depth all --format json # the full transitive closure, machine-readable++# not listed in --help, still there+trail viz [dir] # see the graph: serves an interactive viewer on localhost+trail viz --export site/ --title "PR #12" # one self-contained index.html for CI, GitHub Pages, or a build artifact+trail mcp [dir] # run the MCP server by hand# global-graft --dir <path> # use a context dir other than <repo>/graft-graft --version, -v # print the installed version and exit+trail --dir <path> # use a context dir other than <repo>/graft+trail --version, -v # print the installed version and exit```-Method calls resolve through the receiver's type — constructor assignments+Method calls resolve through the receiver's type, using constructor assignments(`self.router = APIRouter()`) and type annotations, not just the call-site-name — so `callers`/`grep --in` return calls bound to the right+name, so `callers`/`grep --in` return calls bound to the righttype on method-heavy code, not every method anywhere with that name.-## Search & orient (`graft grep` / `graft map`)+## Search & orient (`trail grep` / `trail map`)-`graft grep "<regex>"` is exhaustive over every indexed file and groups hits-by enclosing symbol, ranked by the same in-edge coupling `graft map` uses —-built for "every occurrence of this pattern" tasks where `graft ask`'s+`trail grep "<regex>"` is exhaustive over every indexed file and groups hits+by enclosing symbol, ranked by the same in-edge coupling `trail map` uses.+It's built for "every occurrence of this pattern" tasks where `trail ask`'sranked top-N isn't enough:```@@ -470,73 +729,73 @@ rarelyCalled · function · src/a.ts:L4-L6 · 0 in-edgesL5: console.log("NEEDLE hit in rarelyCalled");```-`graft map` is a token-budgeted first look at a repo — directory clusters-with file/symbol counts, each dir's local hubs, and the global hotspots —+`trail map` is a token-budgeted first look at a repo: directory clusters+with file/symbol counts, each dir's local hubs, and the global hotspots,all ranked by in-degree, no LLM, no key:```-repo map — 113 files · 687 symbols · 2186 edges · typescript+repo map — 313 files · 2349 symbols · 8148 edges · javascript, typescript-src/ 63 files · 527 symbols hubs: contextDirFor (node-file.ts, 21←), wiringPath (write.ts, 14←), buildGraph (build.ts, 11←)-test/ 43 files · 102 symbols hubs: edge (graph-traverse.test.ts, 4←), graphOf (graph-traverse.test.ts, 4←), fileNode (graph-map.test.ts, 3←)-viewer/ 5 files · 58 symbols hubs: $ (main.ts, 9←), activeGraph (main.ts, 5←), cvar (data.ts, 5←)-scripts/ 2 files · 0 symbols+src/ 157 files · 1804 symbols hubs: wiringPath (write.ts, 48←), cmd (brand.ts, 45←), buildGraph (build.ts, 39←)+test/ 144 files · 467 symbols hubs: tmpRepo (helpers.ts, 46←), fetch (app-identity.test.ts, 7←), fakeProviders (helpers.ts, 5←)+viewer/ 5 files · 71 symbols hubs: $ (main.ts, 9←), cvar (data.ts, 6←), activeGraph (main.ts, 5←)+scripts/ 7 files · 7 symbols hubs: bump (graph-quality.mjs, 1←), defaultTranscriptDir (tally-audit.mjs, 1←), flush (tally-audit.mjs, 1←)-hotspots: contextDirFor · function · src/context/node-file.ts:L100-L103 · 21← wiringPath · function · src/graph/write.ts:L20-L22 · 14← buildGraph · function · src/graph/build.ts:L104-L218 · 11← ...+hotspots: wiringPath · function · src/graph/write.ts:L20-L22 · 48← tmpRepo · function · test/helpers.ts:L30-L32 · 46← cmd · function · src/brand.ts:L63-L70 · 45← ...```## Monorepos, submodules & multi-repo folders-Graft supports these layouts:+The graft map supports these layouts:- **A monorepo with one `.git`** (a `pnpm-workspace.yaml`/`package.json`- `workspaces`, or per-package `go.mod`/`pyproject.toml`/`Cargo.toml`) —- `graft build` discovers each sub-project as a ranking scope. `ask`/`map`+ `workspaces`, or per-package `go.mod`/`pyproject.toml`/`Cargo.toml`):+ `trail build` discovers each sub-project as a ranking scope. `ask`/`map`rank every scope on its own terms and fuse the results, so the biggestsub-project can't drown a small one; hits carry `[scope/]` labels, and- `graft map` groups its directory clusters by scope first.-- **A Git superproject with initialized submodules** — submodules stay excluded- by default. Run `graft build --follow-submodules` to fold initialized gitlinks+ `trail map` groups its directory clusters by scope first.+- **A Git superproject with initialized submodules**: submodules stay excluded+ by default. Run `trail build --follow-submodules` to fold initialized gitlinksinto one graph, prefixing child paths (for example,`deps/parser/src/index.ts`) while honoring each submodule's own Git ignorerules. Visible untracked files are included too; uninitialized submodulesremain absent until `git submodule update --init` checks them out. The choiceis saved in `.graft/config.json`, so later no-flag builds and MCP automatic- refreshes behave the same way. Run `graft build --no-follow-submodules` to+ refreshes behave the same way. Run `trail build --no-follow-submodules` torestore and persist the default boundary.-- **A git repo with other repos cloned inside it** (no gitlink, no index entry) — the shape multi-repo manifest tools like `west`, `repo`, `gclient` and `tsrc` check dependencies out into, and the shape you get by cloning an upstream into the tree to patch it locally. `--follow-submodules` cannot reach these: they have no `160000` index entry to follow. Run `graft build --follow-nested-repos` to fold them into one graph, prefixing child paths (for example, `external/parser/src/index.ts`) while honoring each clone's own Git ignore rules. A clone at a git-ignored path stays absent, since Git never reports it. The choice is saved in `.graft/config.json` and is independent of `--follow-submodules` — neither flag implies the other. Run `graft build --no-follow-nested-repos` to restore and persist the default boundary. Prefer this over the multi-repo split below when the nested repos import from each other and you want those edges in one graph; prefer the split when you want each repo scored and refreshed on its own.-- **A folder of separate git repos** (no `.git` at the top) — `graft build`+- **A git repo with other repos cloned inside it** (no gitlink, no index entry): the shape multi-repo manifest tools like `west`, `repo`, `gclient` and `tsrc` check dependencies out into, and the shape you get by cloning an upstream into the tree to patch it locally. `--follow-submodules` cannot reach these: they have no `160000` index entry to follow. Run `trail build --follow-nested-repos` to fold them into one graph, prefixing child paths (for example, `external/parser/src/index.ts`) while honoring each clone's own Git ignore rules. A clone at a git-ignored path stays absent, since Git never reports it. The choice is saved in `.graft/config.json` and is independent of `--follow-submodules`; neither flag implies the other. Run `trail build --no-follow-nested-repos` to restore and persist the default boundary. Prefer this over the multi-repo split below when the nested repos import from each other and you want those edges in one graph; prefer the split when you want each repo scored and refreshed on its own.+- **A folder of separate git repos** (no `.git` at the top): `trail build`auto-splits: each child gets its own (git-ignored) `graft/`, and the parentgets a `graft/workspace.json` index. Queries from the parent federate across- every child, always labeled `<child>/`. Run `graft build` inside a child to+ every child, always labeled `<child>/`. Run `trail build` inside a child towork on just that repo.-In every layout, narrow to one sub-project with `graft ask "<task>" --in <scope>/`+In every layout, narrow to one sub-project with `trail ask "<task>" --in <scope>/`once you know where you're working.-`graft init` at the parent of a multi-repo folder wires **every child repo too**,-not just the parent — an agent session opens at a repo root and reads its+`trail init` at the parent of a multi-repo folder wires **every child repo too**,+not just the parent. An agent session opens at a repo root and reads itsinstruction files from there, so each child needs its own. A session started inthe parent gets the federated view; one started in a child sees that repo alone.Commands also find the graph from a subdirectory: with no `[dir]` argument they-walk up to the nearest `graft/`, so `graft ask` works from `src/deep/inside/`+walk up to the nearest `graft/`, so `trail ask` works from `src/deep/inside/`without a `cd` to the repo root.-## Visualize it (`graft viz`)+## Visualize it (`trail viz`)-`graft viz` opens a local, interactive view of both graphs — no install, no dev+`trail viz` opens a local, interactive view of both graphs. No install, no devserver; the viewer ships prebuilt inside the package.<p align="center">- <img src="assets/graft-viz-demo.gif" alt="graft viz — searching a symbol and jumping to it lights up its dependency graph: amber edges are what it depends on, teal is what depends on it" width="820"/>+ <img src="assets/graft-viz-demo.gif" alt="The graph viewer: searching a symbol and jumping to it lights up its dependency graph: amber edges are what it depends on, indigo is what depends on it" width="820"/><br/><sub>search → jump to a node → dependency graph lights up</sub></p>-- **Context** tab — the architecture graph from `graft/*.md`. Nodes colored by+- **Context** tab: the architecture graph from `graft/*.md`. Nodes colored bytype, sized by connectedness.-- **Code** tab — the per-symbol graph from `graft/.graph/wiring.json` (run `graft build` first).-- **Outline** tab — the file → class → method hierarchy as a collapsible tree.+- **Code** tab: the per-symbol graph from `graft/.graph/wiring.json` (run `trail build` first).+- **Outline** tab: the file → class → method hierarchy as a collapsible tree.Edges speak the code's language. Every link is one of a closed set of verbs, eachanswering a question someone building or reviewing code actually asks:@@ -549,76 +808,21 @@ answering a question someone building or reviewing code actually asks:| `configures` | what changes its behavior without a code change? || `validates` | what checks or judges this? (tests, drift checks, scoring) || `extends` / `implements` | what contract must this honor? |+| `references` | what names this without calling it? (drawn as faint dots) |Select a node and its edges take on direction: **amber = what it depends on,-teal = what depends on it**, with the verb written on each highlighted edge.-Chips above the canvas filter by verb; tree-sitter-extracted edges draw solid-while LLM-inferred ones draw dashed. The viewer live-reloads when `graft/`+indigo = what depends on it**, with the verb written on each highlighted edge.+Chips above the canvas filter by verb; edges the parser resolved exactly draw+solid, while edges matched by name alone, or inferred by the model, draw dashed. The viewer live-reloads when `graft/`changes on disk. Older graphs with vague verbs (`influences`, `supports`) are-normalized on load — no regeneration needed.-------## Tested on your popular repos--The [benchmarks](#benchmark) measure the mechanism. The real test is whether graft helps an agent **ship real changes** on code people actually run, not just answer questions. So we benchmark it on popular open-source repos: **15 tasks each**, 10 real developer questions plus **5 actual implementation tasks** (real merged pull requests, each re-implemented from its base commit and scored against the files the maintainers actually changed). Same agent (Claude Opus), same file tools; the only difference is whether graft is wired in.--Across these repos graft runs **up to 4× cheaper and 3× faster**, with better or no loss of correctness: it reproduces the real merged PRs by touching the same files the maintainers did. Per-repo detail below.--### PocketBase (Go, ~350 files)--| Aggregate over 15 tasks | Standard Claude Code | With graft |-|---|---|---|-| Cost | $13.91 | **$11.02 (−21%)** |-| Wall-clock | 2,044s | **1,762s (−14%)** |-| PRs reproduced | 5 / 5 | **5 / 5 (same files as the maintainers)** |--Cheaper and faster with no loss of correctness: graft reproduced all five merged PRs, touching the same files the maintainers did. The gap is widest on cross-file understanding — "how does auth work across OAuth2 providers" dropped from $2.19 to $0.84.--<details>-<summary><b>The 10 questions we asked</b></summary>--1. **Orientation** — Give me a map of PocketBase's architecture: the main subsystems and how an HTTP request flows through to the database.-2. **Entry-point trace** — Trace end-to-end what happens when a client creates a record via the REST API, from route handler to database write.-3. **Feature location** — I want to add a brand-new collection field type. Where do I hook it in, and which pieces must change?-4. **Bug localization** — Realtime subscriptions silently stop delivering events after a while. Where would you start looking, and why?-5. **Blast radius** — If I change the signature of the record-validation logic, what depends on it and what could break?-6. **Cross-file synthesis** — How does auth work across OAuth2 providers: where are tokens issued, validated, stored, and refreshed?-7. **Extensibility** — How do I use PocketBase as a Go framework to register a custom route plus an on-record-create hook?-8. **Security discovery** — Where is user input validated, and where are collection API access rules enforced before a query runs?-9. **Public API** — As an external app, how do I authenticate and then list and filter records over the REST API?-10. **Test verification** — Where are the tests for the record CRUD API, and what do they assert about access rules?--</details>--<details>-<summary><b>The 5 merged PRs we re-implemented</b></summary>--Each PR was reset to its base commit; graft's diff was scored against the files the merged PR changed.--| PR | Type | What it does | Files the maintainers touched |-|---|---|---|---|-| [#6744](https://github.com/pocketbase/pocketbase/pull/6744) | feat | Generate & serve WebP thumbnails | `apis/file.go`, `tools/filesystem/filesystem.go` |-| [#6947](https://github.com/pocketbase/pocketbase/pull/6947) | fix | Uniform char distribution in regex random strings | `tools/security/random_by_regex.go` |-| [#6690](https://github.com/pocketbase/pocketbase/pull/6690) | refactor | Patreon OAuth2 to use `x/oauth2/endpoints` | `tools/auth/patreon.go` |-| [#2726](https://github.com/pocketbase/pocketbase/pull/2726) | perf | Drop a redundant admin-count query on a hot middleware path | `apis/middlewares.go` |-| [#3192](https://github.com/pocketbase/pocketbase/pull/3192) | fix | Restore prior API rules on automigration rollback | `plugins/migratecmd/templates.go` |--</details>--<details>-<summary><b>Method</b></summary>--Two clones of PocketBase at the same commit: one wired with `graft init`, one untouched and verified graft-free. Each task run headless (`claude -p`, Claude Opus) with an empty MCP config. Understanding questions were graded by whether the answer pointed to the right files and functions; PR tasks were scored on whether the agent's diff touched the same files as the merged PR. Every transcript was audited to confirm graft was actually used in the graft arm and absent from the standard arm.--</details>+normalized on load, so no regeneration is needed.---## Development```bash-git clone https://github.com/NanoNets/context-graph-engine.git && cd context-graph-engine+git clone https://github.com/trailhq/Trail-Code.git && cd Trail-Codenpm installnpm run buildnpm testdiff --git a/SECURITY.md b/SECURITY.mdindex 87af0b6e..d2c01c1e 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -2,16 +2,16 @@## Supported Versions-Graft is pre-1.0 and ships continuously from `main`. Security fixes are made against-the latest published npm release (`@nanonets/graft`); older versions are not-separately patched.+Trail-code (formerly graft) is pre-1.0 and ships continuously from `main`. Security+fixes are made against the latest published npm release (`@trailhq/trail`, also+published as `@nanonets/graft`); older versions are not separately patched.## Reporting a VulnerabilityPlease do not open a public GitHub issue for security vulnerabilities.Report vulnerabilities privately via-[GitHub Security Advisories](https://github.com/NanoNets/Graft/security/advisories/new),+[GitHub Security Advisories](https://github.com/trailhq/Graft/security/advisories/new),or email [email protected].We'll acknowledge your report within 3 business days and aim to ship a fix ordiff --git a/TELEMETRY.md b/TELEMETRY.mdindex bf9d8b19..079b017f 100644--- a/TELEMETRY.md+++ b/TELEMETRY.md@@ -1,19 +1,23 @@# Telemetry-graft collects a small set of **anonymous** usage events so we can tell whether+Trail-code collects a small set of **anonymous** usage events so we can tell whetherthe thing works: how many repos get past a build, whether an agent reaches for-graft or falls back to grep, which commands earn their place, and what breaks in+Trail-code or falls back to grep, which commands earn their place, and what breaks inthe wild.This document is the complete, authoritative contract: **if an event or property-is not listed here, graft does not send it.** The implementation lives in+is not listed here, Trail-code does not send it.** The implementation lives in[`src/telemetry/contract.ts`](src/telemetry/contract.ts) and enforces this listas a hard allowlist — unknown events and unknown properties are dropped beforeanything is written, let alone sent. The code and this file are kept inlockstep, and because the repo is open source you can verify that yourself.+This page covers anonymous usage stats only. A Trail workspace you choose to+connect is separate, and sends more: see+[What stays on your machine](README.md#what-stays-on-your-machine).+Nothing is ever sent from a command you run. Events are appended to a local file-and a detached background process posts them at most once a day, so no `graft+and a detached background process posts them at most once a day, so no `trailask` ever waits on the network.The one exception is the `install` event below, which the npm postinstall hook@@ -28,12 +32,12 @@ Every event carries only these common properties:| Property | Example | Notes || --- | --- | --- |-| `app_version` | `0.12.0` | The graft version that produced the event |+| `app_version` | `0.12.0` | The Trail-code version that produced the event || `os` | `darwin` / `win32` / `linux` | Platform, nothing more || `arch` | `arm64` / `x64` | CPU architecture || `node_major` | `20` | Major version only || `ci` | `false` | Always false — CI never sends (see below) |-| `agent_host` | `claude-code` / `cursor` / `mcp` / `cli` | Which surface graft ran under |+| `agent_host` | `claude-code` / `cursor` / `mcp` / `cli` | Which surface Trail-code ran under || `cli_name` | `trail` / `graft` | Which of the two names started the process (graft is trail's old name) || `repo_id` | a random UUID | See "How it stays anonymous" |@@ -42,11 +46,11 @@ The events:| Event | Extra properties | When || --- | --- | --- || `install` | `global` (`true` for `npm i -g`, `false` for a project dependency) | The npm postinstall hook runs — once per machine per version |-| `first_run` | — | Once, the first time a graft command runs on a machine |-| `init_completed` | `agents` (the ids you selected, sorted), `consent` | `graft init` finishes |+| `first_run` | — | Once, the first time a `trail` or `graft` command runs on a machine |+| `init_completed` | `agents` (the ids you selected, sorted), `consent` | `trail init` finishes || `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 |+| `query` | `command`, `surface` (`cli`/`mcp`/`hook`), `hit` (`ask` only), `notes` (`0`/`1`/`2`, how many learnings `ask` showed; only in a repo that keeps learnings) | Any query command || `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`) || `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 |@@ -54,8 +58,8 @@ The events:| `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 || `learnings_committed` | `added_bucket`, `total_bucket` (learnings committed on `HEAD`, bucketed), `first_look` (`true`/`false`) | A Claude Code session starts in a repo trail runs in and more learnings are committed there than at the last session. Their names and text are never sent || `cold_start` | `outcome` (`found`/`none_found`/`no_sessions`/`no_claude`/`failed`), `sessions_bucket`, `offered_bucket`, `picked_bucket` (how many it saved), `duration_bucket`, `model` | `trail init` reads your past Claude Code sessions in the repo, once, for things you told Claude more than once, and saves them as learnings. The reading is done by your own Claude Code; your messages and what it found are never sent to trail |-| `takeaway_saved` | `new_skill` (`true`/`false`) | `trail learn` saves a correction as a takeaway on a skill, on this machine (`~/.trail/`). Its text is never sent |-| `skills_folded` | `takeaways_bucket` (how many takeaways were folded, bucketed) | `trail skills fold` writes takeaways into a skill's SKILL.md |+| `takeaway_saved` | `new_skill` (`true`/`false`) | `trail learn` adds a correction to a skill, on this machine (`~/.trail/`). Its text is never sent |+| `skills_folded` | `takeaways_bucket` (how many corrections were folded, bucketed) | `trail skills fold` writes waiting corrections into a skill's SKILL.md || `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@@ -86,25 +90,25 @@ An example event, in full:}```-Run `graft telemetry debug` to print the exact batch your machine would send. It+Run `trail telemetry debug` to print the exact batch your machine would send. Itsends nothing.-### One thing graft reads locally+### One thing Trail-code reads locallyTwo of those properties — `graft_turns_bucket` and `reported_turns_bucket` — needto know something the others don't: whether the reply you actually read said what-graft saved. graft computes a saving on every retrieval call, but a turn that+Trail-code saved. Trail-code computes a saving on every retrieval call, but a turn thatsaves 20,000 tokens in silence and a turn that saves nothing look identical in`saved_tokens_bucket`, and that difference is the whole question.The agent's own prose lives in one place a hook can reach: the transcript fileyour editor writes, named on the Stop hook's stdin. So at the end of a turn that-used graft, graft reads the tail of that file, checks the reply for a "graft saved+used Trail-code, it reads the tail of that file, checks the reply for a "saved~N tokens" line, and increments one of two counters. Nothing out of the file isstored, and nothing out of it is sent — not the reply, not a fragment of it, notits length. Two counts of turns cross the wire, as buckets, once per session.-A turn graft cannot check — an editor whose Stop hook names no transcript, an+A turn Trail-code cannot check — an editor whose Stop hook names no transcript, anunreadable file — is counted in neither total, so the ratio always means "of theturns we could read".@@ -112,9 +116,9 @@ turns we could read".No source code. No file paths, repo names, organisation names, git remotes, orbranch names. No symbol names, node summaries, or anything out of the graph. No-query strings, prompts, or agent output — graft reads the last reply of a-graft-using turn locally to decide whether it mentioned the saving (see "One-thing graft reads locally"); only the resulting count is sent, never the text. No error messages or stack traces — a+query strings, prompts, or agent output — Trail-code reads the last reply of a+turn that used it locally to decide whether it mentioned the saving (see "One+thing Trail-code reads locally"); only the resulting count is sent, never the text. No error messages or stack traces — afailure contributes a code from a fixed list and nothing else. No environmentvariables, API keys, model names, hostnames, usernames, or email addresses.@@ -136,12 +140,12 @@ variables, API keys, model names, hostnames, usernames, or email addresses.Any one of these fully disables telemetry:-1. **Uncheck "anonymous usage stats" in the `graft init` picker.** Takes effect+1. **Uncheck "anonymous usage stats" in the `trail init` picker.** Takes effectimmediately and is remembered for this machine.-2. **`graft telemetry disable`** at any time. `graft telemetry status` shows the- current state, and `graft telemetry enable` turns it back on.+2. **`trail telemetry disable`** at any time. `trail telemetry status` shows the+ current state, and `trail telemetry enable` turns it back on.3. **Set [`DO_NOT_TRACK`](https://web.archive.org/web/20251005054121/https://consoledonottrack.com/)** to any value other- than `0`. Respected unconditionally — it outranks graft's own setting.+ than `0`. Respected unconditionally — it outranks Trail-code's own setting.4. **Run in CI.** `CI`, `GITHUB_ACTIONS`, `GITLAB_CI` and friends switch it offwithout being asked. A build server is not a user.5. **Build from source.** The PostHog key is stamped in only at publish time@@ -152,7 +156,7 @@ Any one of these fully disables telemetry:## Where the events goOfficial builds send to `https://events.nanonets.com`, Nanonets' own PostHog-front door, so graft's numbers sit in the same project as the rest of the+front door, so Trail-code's numbers sit in the same project as the rest of theproduct rather than in a separate one. The client posts a single batch to`/batch/`.diff --git a/assets/graft-cold-vs-graft-dark.png b/assets/graft-cold-vs-graft-dark.pngdeleted file mode 100644index 07433c92..00000000Binary files a/assets/graft-cold-vs-graft-dark.png and /dev/null differdiff --git a/assets/graft-cold-vs-graft.png b/assets/graft-cold-vs-graft.pngdeleted file mode 100644index c2b02a0e..00000000Binary files a/assets/graft-cold-vs-graft.png and /dev/null differdiff --git a/assets/graft-comparison-demo.gif b/assets/graft-comparison-demo.gifdeleted file mode 100644index 1bb59a84..00000000Binary files a/assets/graft-comparison-demo.gif and /dev/null differdiff --git a/assets/graft-hero.png b/assets/graft-hero.pngdeleted file mode 100644index cb0f9535..00000000Binary files a/assets/graft-hero.png and /dev/null differdiff --git a/assets/graft-hooks-demo.gif b/assets/graft-hooks-demo.gifdeleted file mode 100644index 619ee69d..00000000Binary files a/assets/graft-hooks-demo.gif and /dev/null differdiff --git a/assets/graft-site-act-demo.gif b/assets/graft-site-act-demo.gifdeleted file mode 100644index 61c9476a..00000000Binary files a/assets/graft-site-act-demo.gif and /dev/null differdiff --git a/assets/graft-terminal.png b/assets/graft-terminal.pngdeleted file mode 100644index c5dd0239..00000000Binary files a/assets/graft-terminal.png and /dev/null differdiff --git a/assets/trail-code-how-it-works-dark.webp b/assets/trail-code-how-it-works-dark.webpnew file mode 100644index 00000000..f8f87f90Binary files /dev/null and b/assets/trail-code-how-it-works-dark.webp differdiff --git a/assets/trail-code-how-it-works.webp b/assets/trail-code-how-it-works.webpnew file mode 100644index 00000000..ad8cb876Binary files /dev/null and b/assets/trail-code-how-it-works.webp differdiff --git a/docs/github-app.md b/docs/github-app.mdindex b76bdc70..a8df07b0 100644--- a/docs/github-app.md+++ b/docs/github-app.md@@ -1,4 +1,4 @@-# The graft GitHub App+# The Trail-code GitHub AppPosts a blast-radius comment on every pull request, and hosts the interactivegraph behind a signed link.diff --git a/package-lock.json b/package-lock.jsonindex 7150c197..842d8a76 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "@nanonets/graft",- "version": "0.21.1",+ "version": "0.22.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@nanonets/graft",- "version": "0.21.1",+ "version": "0.22.0","hasInstallScript": true,"license": "MIT","dependencies": {diff --git a/package.json b/package.jsonindex fa58b0d9..98e6d94e 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@nanonets/graft",- "version": "0.21.1",+ "version": "0.22.0","description": "Build a repo's context graph as a folder of linked markdown files: a local, regenerable cache that every query keeps in sync with your code.","keywords": ["ai",@@ -14,11 +14,11 @@"license": "MIT","repository": {"type": "git",- "url": "git+https://github.com/trailhq/Graft.git"+ "url": "git+https://github.com/trailhq/Trail-Code.git"},- "homepage": "https://github.com/trailhq/Graft#readme",+ "homepage": "https://github.com/trailhq/Trail-Code#readme","bugs": {- "url": "https://github.com/trailhq/Graft/issues"+ "url": "https://github.com/trailhq/Trail-Code/issues"},"publishConfig": {"access": "public"diff --git a/scripts/pack-trail.mjs b/scripts/pack-trail.mjsindex fb98c103..913fdd04 100644--- a/scripts/pack-trail.mjs+++ b/scripts/pack-trail.mjs@@ -1,10 +1,10 @@/**- * Lays out the `@trailhq/trail` package from this repo's build, in build/trail/.+ * Lays out the `@trailhq/trail-code` package from this repo's build, in build/trail/.** trail and graft are one program under two names, published as two packages* from the same `dist/`:*- * @trailhq/trail bin: trail → dist/bin/trail.js+ * @trailhq/trail-code bin: trail → dist/bin/trail.js* @nanonets/graft bin: graft → dist/bin/graft.js (this repo's package.json)** Each package ships exactly one command, so installing both never clashes on@@ -32,7 +32,7 @@ if (!existsSync(join(root, 'dist', 'bin', 'trail.js'))) {const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));const trail = {...pkg,- name: '@trailhq/trail',+ name: '@trailhq/trail-code',description:"Your team's shared memory for coding agents: a code map on your machine, and the learnings, decisions and skills your whole team shares. Formerly graft.",keywords: [...new Set(['trail', ...(pkg.keywords ?? [])])],diff --git a/scripts/postinstall.mjs b/scripts/postinstall.mjsindex ae92f5e3..f50d7851 100644--- a/scripts/postinstall.mjs+++ b/scripts/postinstall.mjs@@ -7,14 +7,14 @@ import { fileURLToPath, pathToFileURL } from 'node:url';const root = dirname(dirname(fileURLToPath(import.meta.url)));-// The same code ships as @trailhq/trail (the `trail` command) and as+// The same code ships as @trailhq/trail-code (the `trail` command) and as// @nanonets/graft (`graft`, its old name). The install event and the nudge say// which one this is.let pkgName = '@nanonets/graft';try {pkgName = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).name ?? pkgName;} catch { /* the graft defaults */ }-const isTrail = pkgName === '@trailhq/trail';+const isTrail = pkgName === '@trailhq/trail-code';if (isTrail) process.env.TRAIL_INVOKED_AS = 'trail';/**diff --git a/src/app/sources.ts b/src/app/sources.tsindex 48017e10..b085145d 100644--- a/src/app/sources.ts+++ b/src/app/sources.ts@@ -215,10 +215,10 @@ export function skillFiles(root: string, max = MAX_SKILL_FILES): string[] {return out;}-/** Remove graft's own fenced regions, so the brain never learns graft from graft. */+/** Remove graft's own fenced regions (trail's too), so the brain never learns graft from graft. */function stripManagedBlocks(text: string): string {return text- .replace(/<!--\s*graft:(brain:)?start\s*-->[\s\S]*?<!--\s*graft:(brain:)?end\s*-->/g, "")+ .replace(/<!--\s*(graft|trail):(brain:)?start\s*-->[\s\S]*?<!--\s*\1:(brain:)?end\s*-->/g, "").trim();}diff --git a/src/blast/blast-cli.ts b/src/blast/blast-cli.tsindex 73577bfc..231d8bdb 100644--- a/src/blast/blast-cli.ts+++ b/src/blast/blast-cli.ts@@ -12,6 +12,7 @@ import type { GraphV1 } from "../graph/types.js";import { blastRadiusIn, type BlastReport } from "./blast.js";import { changedFiles, refExists } from "./diff.js";import { markdownReport, mermaidDiagram, textReport } from "./render.js";+import { cmd } from "../brand.js";export type BlastFormat = "text" | "markdown" | "mermaid" | "json";@@ -68,7 +69,7 @@ export async function runBlastCommand(dir: string, opts: BlastCliOptions): Promiconst graph = loadGraphCached(contextDir);if (!graph) {- console.error(`✗ no graph found at ${contextDir} — run \`graft build\` first`);+ console.error(`✗ no graph found at ${contextDir} — run \`${cmd("graft build")}\` first`);process.exit(1);}diff --git a/src/blast/render.ts b/src/blast/render.tsindex 9f6fbe1b..36d2635e 100644--- a/src/blast/render.ts+++ b/src/blast/render.ts@@ -16,6 +16,7 @@ import type { BlastReport, ChangedArea, ImpactedModule, Impacted, TestSignal } fimport type { Evidence } from "../viz/assemble.js";import { fileReader, impactedEvidence, reachTerms } from "./evidence.js";import { MAX_REVIEWERS, mention, sinceLabel, type Owner } from "./owners.js";+import { brand, cmd } from "../brand.js";/** Diagram cap. Everything past it folds into one aggregate circle carrying the* dropped counts, so the picture shrinks but never lies. */@@ -116,7 +117,7 @@ export function markdownReport(r: BlastReport, opts: { root?: string } = {}): stconst out: string[] = [];const symbols = r.modules.reduce((n, m) => n + m.symbols.length, 0);- out.push("### 🌱 graft blast radius");+ out.push(`### 🌱 ${brand()} blast radius`);out.push("");out.push(headline(r, symbols));const testLine = testHeadline(r);@@ -155,7 +156,7 @@ export function markdownReport(r: BlastReport, opts: { root?: string } = {}): stfor (const line of caveats) out.push(line);}out.push("");- out.push(`<sub>\`graft blast\` · ${r.basis} · ${depthLabel(r.depth)} · ${plural(r.changed.length, "changed file")}</sub>`);+ out.push(`<sub>\`${cmd("graft blast")}\` · ${r.basis} · ${depthLabel(r.depth)} · ${plural(r.changed.length, "changed file")}</sub>`);return out.join("\n") + "\n";}diff --git a/src/brand.ts b/src/brand.tsindex ef583fc8..8f11434e 100644--- a/src/brand.ts+++ b/src/brand.ts@@ -27,7 +27,7 @@ export const BRAND_ENV = "TRAIL_INVOKED_AS";/** The npm package each name is published as. Same code, two names. */export const PACKAGE_FOR: Record<Brand, string> = {- trail: "@trailhq/trail",+ trail: "@trailhq/trail-code",graft: "@nanonets/graft",};@@ -104,11 +104,19 @@ export function repoWiredForTrail(dir: string): boolean {* entry has set a name. They say trail in a repo wired for it, but only when* the `trail` command is installed on this machine: a hook that tells the* agent to run a command the machine doesn't have costs a failed tool call.- * A name already set (by the CLI that spawned this) is kept.+ * A name already set (by the CLI that spawned this) is kept. `wiredElsewhere`+ * also counts a repo whose other agents' files are on trail (hosts/registry.ts's+ * `hostsWiredForTrail`, passed in so this file stays light): Cursor's and+ * Codex's hooks run this same entry in repos with no `.claude` at all.*/-export function adoptRepoBrand(repo: string, env: NodeJS.ProcessEnv = process.env): Brand {+export function adoptRepoBrand(+ repo: string,+ env: NodeJS.ProcessEnv = process.env,+ wiredElsewhere?: (repo: string) => boolean,+): Brand {if (env[BRAND_ENV] !== "trail" && env[BRAND_ENV] !== "graft") {- setBrand(repoWiredForTrail(repo) && trailOnPath(env) ? "trail" : "graft", env);+ const wired = repoWiredForTrail(repo) || Boolean(wiredElsewhere?.(repo));+ setBrand(wired && trailOnPath(env) ? "trail" : "graft", env);}return brand(env);}@@ -184,3 +192,76 @@ export function graftNotice(input: NoticeInput): string | null {if (!trailOnPath(env)) lines.push("· run graft upgrade to get the trail command too");return lines.join("\n");}++/** The nearest directory at or above `dir` holding a `.git`, or null. */+function gitRootOf(dir: string): string | null {+ for (let at = dir; ; at = dirname(at)) {+ if (existsSync(join(at, ".git"))) return at;+ if (dirname(at) === at) return null;+ }+}++/**+ * The line a person typing `trail` sees in a repo an older graft wired, while+ * nothing on this machine can reach that wiring; or null.+ *+ * A graft 0.21 or older committed hook shims that look for `@nanonets/graft`+ * alone, and registered a bare `graft mcp` server. On a machine with trail and+ * no graft, the hooks run and do nothing and the server never starts, so the+ * session start that would move the repo to trail never happens. `trail init`+ * in the repo moves it, and so does a session opened under the hooks+ * `trail init` writes to `~/.claude`; this says so to someone who has done+ * neither. Silent once graft is on PATH, since its hooks then move the repo.+ * Never shown to an agent, a pipe or CI, like {@link graftNotice}.+ */+export function strandedRepoNotice(input: { cwd: string; tty: boolean; env?: NodeJS.ProcessEnv }): string | null {+ const env = input.env ?? process.env;+ if (brand(env) !== "trail" || !input.tty) return null;+ if (env.CLAUDECODE !== undefined || env.CI) return null;+ const repo = gitRootOf(input.cwd);+ if (!repo || repoWiredForTrail(repo) || commandOnPath("graft", env)) return null;+ try {+ if (readFileSync(join(repo, ".claude", "helpers", "graft-hooks.cjs"), "utf8").includes(PACKAGE_FOR.trail)) return null;+ } catch {+ return null; // no graft wiring here+ }+ return "· this repo's agent hooks were set up by an older graft and can't find trail. run trail init here once to move the repo over";+}++const WEEK_MS = 7 * DAY_MS;++export function handoverStampPath(home: string = homedir()): string {+ return join(home, ".graft", "trail-handover.json");+}++/**+ * The line a Claude Code session start hands the agent on a machine that has+ * graft but not the trail command, at most once a week; or null.+ *+ * {@link graftNotice} reaches a person typing graft. Most people only meet+ * graft through their agent, so the agent is the one who can tell them that+ * `graft upgrade` adds trail. Once trail is installed, the next session moves+ * the repo over by itself (see upkeep-run.ts), so this stops.+ */+export function trailHandoverLine(input: { env?: NodeJS.ProcessEnv; home?: string; now?: number } = {}): string | null {+ const env = input.env ?? process.env;+ if (brand(env) !== "graft" || env.CI || env.GRAFT_NO_RENAME_NOTICE || trailOnPath(env)) return null;+ const now = input.now ?? Date.now();+ const path = handoverStampPath(input.home);+ try {+ const last = (JSON.parse(readFileSync(path, "utf8")) as { shownAt?: number }).shownAt ?? 0;+ if (now - last < WEEK_MS) return null;+ } catch {+ /* never shown */+ }+ try {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, JSON.stringify({ shownAt: now }) + "\n");+ } catch {+ /* shown again next time */+ }+ return (+ "· graft is now Trail-code: the same code map under the `trail` command, plus learnings the team shares in .trail/. " ++ "Tell the user once, in a line at the end of your first reply, that `graft upgrade` adds it and graft keeps working."+ );+}diff --git a/src/claude/format.ts b/src/claude/format.tsindex d1d0550c..d776dd78 100644--- a/src/claude/format.ts+++ b/src/claude/format.ts@@ -79,7 +79,7 @@ export function formatBlastRadius(w: GraphV1, filePath: string, cap = 8): stringreturn ` • ${e.relation} ← ${label}`;});const more = edges.length > cap ? `\n • +${edges.length - cap} more` : '';- return `[graft] blast radius for ${basename(filePath)}, who depends on it:\n${items.join('\n')}${more}`;+ return `${tag()} blast radius for ${basename(filePath)}, who depends on it:\n${items.join('\n')}${more}`;}export interface AskJson {@@ -220,8 +220,8 @@ export function weakMatchNudge(s: SessionState, strong: number): string | null {if (spent >= NUDGE_CAP) return null;s.nudges = spent + 1;return (- `[graft] no strong match for this prompt (name-field match ${strong.toFixed(2)}) — the graph ` +- `has more than this probe found. Run \`graft ask "<your task>" --source\` before grepping.`+ `${tag()} no strong match for this prompt (name-field match ${strong.toFixed(2)}) — the graph ` ++ `has more than this probe found. Run \`${cmd('graft ask')} "<your task>" --source\` before grepping.`);}diff --git a/src/claude/hook-layers.ts b/src/claude/hook-layers.tsnew file mode 100644index 00000000..0e9582b3--- /dev/null+++ b/src/claude/hook-layers.ts@@ -0,0 +1,66 @@+/**+ * Which copy of the hooks answers an event when both are registered.+ *+ * `init` wires Claude Code twice: in the repo (`.claude/settings.json`, committed+ * for teammates) and in `~/.claude` (the floor for worktrees and ignored files,+ * see hosts/claude-global.ts). Claude Code runs both, so every prompt got its+ * learnings twice and the ask to save one came twice in a session. The+ * `~/.claude` copy runs in every folder, trusted or not, so when it covers an+ * event the repo's copy stands down for it.+ *+ * Only a `~/.claude` shim that can find trail counts: one an older graft wrote+ * looks for `@nanonets/graft` alone, and standing down for it would leave a+ * trail-only machine with no hooks at all. The next session start rewrites it.+ *+ * Reads two small files and imports nothing heavier than node:fs, since every+ * hook loads it.+ */+import { existsSync, readFileSync } from "node:fs";+import { homedir } from "node:os";+import { basename, dirname, join, resolve } from "node:path";+import { PACKAGE_FOR } from "../brand.js";++/** `node "<shim>" <event>`, the form hosts/claude-global.ts writes. */+const COMMAND = /^node\s+"([^"]+)"\s+(\S+)$/;++/**+ * True when this hook process runs from the repo's shim and the `~/.claude`+ * copy also answers `event`, so this one should do nothing.+ *+ * `shim` is the path the hook was started from (`process.argv[1]`).+ */+export function globalCopyCovers(event: string, shim: string | undefined, home: string = homedir()): boolean {+ if (!shim) return false;+ const at = resolve(dirname(shim));+ // Only Claude Code's repo copy: Cursor's and Codex's shims call the same+ // entry, and Claude's ~/.claude hooks never run for them.+ if (basename(at) !== "helpers" || basename(dirname(at)) !== ".claude") return false;+ const helpers = resolve(home, ".claude", "helpers");+ if (at === helpers) return false; // this is the ~/.claude copy+ let settings: { hooks?: Record<string, unknown> };+ try {+ settings = JSON.parse(readFileSync(join(home, ".claude", "settings.json"), "utf8"));+ } catch {+ return false;+ }+ for (const groups of Object.values(settings?.hooks ?? {})) {+ if (!Array.isArray(groups)) continue;+ for (const group of groups) {+ for (const hook of (group as { hooks?: Array<{ command?: unknown }> })?.hooks ?? []) {+ const m = typeof hook?.command === "string" ? COMMAND.exec(hook.command.trim()) : null;+ if (!m || m[2] !== event || resolve(dirname(m[1]!)) !== helpers) continue;+ if (findsTrail(m[1]!)) return true;+ }+ }+ }+ return false;+}++/** The shim exists and is one that looks for the trail package. */+function findsTrail(shim: string): boolean {+ try {+ return existsSync(shim) && readFileSync(shim, "utf8").includes(PACKAGE_FOR.trail);+ } catch {+ return false;+ }+}diff --git a/src/claude/hooks.ts b/src/claude/hooks.tsindex 214d7022..6fd80bca 100644--- a/src/claude/hooks.ts+++ b/src/claude/hooks.ts@@ -10,13 +10,15 @@ import { indexFreshness, staleBanner } from '../context/check.js';import { patchStats, readStats, acquireLock, readSession, writeSession, resolveContextDir } from './state.js';import { graftCliPath, claudeScriptPath } from './paths.js';import { runUpkeep } from '../upkeep-run.js';-import { runningVersion } from '../upkeep.js';+import { runningVersion, wiredHostIds } from '../upkeep.js';+import { hostsWiredForTrail } from '../hosts/registry.js';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 { adoptRepoBrand, brand, cmd, commandOnPath, repoWiredForTrail, tag, trailOnPath } from '../brand.js';+import { adoptRepoBrand, brand, cmd, commandOnPath, repoWiredForTrail, tag, trailHandoverLine, trailOnPath } from '../brand.js';import { fitTrailServerToMachine } from '../hosts/claude-global.js';+import { globalCopyCovers } from './hook-layers.js';import { NOTE_CALL } from '../notes/session-cost.js';import { keepsNotes, noteCount, repoPlace } from '../notes/home.js';import { branchesStale, refreshBranches, SESSION_REFRESH_MS } from '../notes/branches.js';@@ -572,9 +574,11 @@ function trailAtStart(dir: string): void {export async function main(event: string): Promise<void> {// trail's own headless Claude calls (the first-run read of past sessions) run with this set.if (process.env.TRAIL_NO_HOOKS === '1') return;+ // Registered in the repo and in ~/.claude, Claude Code runs both: one answers.+ if (globalCopyCovers(event, process.argv[1])) return;const input = readStdin();const dir = projectDir(input);- adoptRepoBrand(dir);+ adoptRepoBrand(dir, process.env, hostsWiredForTrail);if (event === 'session-start') {// Before anything is emitted: refresh this repo's wiring if it was written by@@ -582,6 +586,10 @@ export async function main(event: string): Promise<void> {// 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;+ // On graft without trail, in a repo graft set up: once a week, the agent+ // tells the person how to get it.+ const handover = wiredHostIds(dir).includes('claude') ? trailHandoverLine() : null;+ if (handover) upkeep.push(handover);// Roll up any session that ended since we were last here. Queue-only — the// hook still sends nothing; the CLI or the MCP server sends it later.flushClosedSessions(dir);diff --git a/src/claude/session-metrics.ts b/src/claude/session-metrics.tsindex cf9b3b84..3e970024 100644--- a/src/claude/session-metrics.ts+++ b/src/claude/session-metrics.ts@@ -36,6 +36,7 @@ import { dollarsSaved, formatDollars } from '../context/price.js';import { readSession, writeSession, sessionDir, listSessionIds, type SessionState } from './state.js';import type { AgentHost } from '../telemetry/contract.js';import { GRAFT_MCP_TOOL_NAMES } from '../mcp/tool-names.js';+import { brand, cmd } from '../brand.js';export type ToolKind = 'graft' | 'source';@@ -79,7 +80,7 @@ export function commandInvokesGraft(command: string): boolean {// running from a source checkoutif (/dist[/\\](cli|bin[/\\](trail|graft))\.js/.test(c)) return true;// `graft …`, `graft-dev …`, `npx [-y] [@nanonets/]graft …`, and the same for- // `trail` / `@trailhq/trail`, at the start of the line or of a &&/;/| segment —+ // `trail` / `@trailhq/trail-code`, at the start of the line or of a &&/;/| segment —// not "mygraft" or a path that merely contains it.return /(^|[|&;]\s*)(npx\s+(-y\s+)?(@nanonets\/|@trailhq\/)?)?(graft|trail)(-dev)?\b/i.test(c);}@@ -188,7 +189,7 @@ export function sessionInputRate(dir: string): number | null {export function formatSessionStats(s: SessionSummary | null): string {if (s === null) {- return 'graft stats: no session recorded yet — use graft in an agent session, then look again.';+ return `${cmd('graft stats')}: no session recorded yet — use ${brand()} in an agent session, then look again.`;}const graft = s.graftReads ?? 0;const source = s.sourceReads ?? 0;@@ -197,7 +198,7 @@ export function formatSessionStats(s: SessionSummary | null): string {const mix =total === 0 ? 'no retrieval yet' : `${Math.round((graft / total) * 100)}% graft`;const lines = [- `graft stats — session ${s.id}`,+ `${cmd('graft stats')} — session ${s.id}`,` graft reads: ${graft}`,` source reads: ${source} (Read / Grep / Glob)`,` mix: ${mix}`,diff --git a/src/claude/shim-template.ts b/src/claude/shim-template.tsindex 3855786c..44b9a2b5 100644--- a/src/claude/shim-template.ts+++ b/src/claude/shim-template.ts@@ -49,9 +49,10 @@ const { pathToFileURL } = require('url');const { execFileSync } = require('child_process');const dir = process.env.CLAUDE_PROJECT_DIR || process.cwd();-// The same code ships as @trailhq/trail and as @nanonets/graft, its old name;-// either one answers, and the newer wins.-const PKGS = ['@trailhq/trail', '@nanonets/graft'];+// The same code ships as @trailhq/trail-code and as @nanonets/graft, its old name;+// either one answers, and the newer wins. @trailhq/trail is what builds from+// source were called before the package was published.+const PKGS = ['@trailhq/trail-code', '@nanonets/graft', '@trailhq/trail'];const BINS = process.platform === 'win32' ? ['trail.cmd', 'graft.cmd'] : ['trail', 'graft'];// The dist/claude dir this machine's last init ran from, kept in the trail homediff --git a/src/claude/skill-template.ts b/src/claude/skill-template.tsindex 75391d1f..97cea4f2 100644--- a/src/claude/skill-template.ts+++ b/src/claude/skill-template.ts@@ -1,4 +1,4 @@-import type { Brand } from "../brand.js";+import { cmd, type Brand } from "../brand.js";// The graft Claude Code skill, bundled as a string so `graft init` can write it into a// consumer repo's .claude/skills/graft/SKILL.md (no network fetch, version-locked to the// installed graft). This is the single source of truth for the skill text; graft's own@@ -28,7 +28,7 @@ const TRAIL_DESCRIPTION = `Use for ANY task in this repo. What past sessions worcorrects how something is done here. Run trail check before you commit,push or open a PR. If the trail command isn't installed, read.trail/learnings/ directly and tell the user once that npm install -g- @trailhq/trail adds search, checks and their team's view.`;+ @trailhq/trail-code adds search, checks and their team's view.`;/** The same moments, first in the body, so they're read before the tool docs. */const TRAIL_MOMENTS = `## When to reach for trail@@ -49,26 +49,38 @@ The learnings are plain markdown in \`.trail/learnings/\`, one file per session,with what it decided, tried and ruled out, and which files it's about(\`touches:\`). Grep them for your task's files and words, and read the onesthat match before exploring. Tell the user once, in a line at the end of a-reply, that \`npm install -g @trailhq/trail\` gives them search, the check+reply, that \`npm install -g @trailhq/trail-code\` gives them search, the checkbefore review, and their team's view. Don't ask again in the same session.## The code map`;/**- * The graft text with trail's spelling. The code map still lives in `graft/`,- * so a `graft` followed by `/` is a path and stays; `graft check` became- * `trail build --check`. Trail has its own frontmatter and opens with the- * moments to reach for it. Then the parts only trail has: learnings,- * corrections and the check before work goes for review.+ * Agent-facing graft text in trail's spelling, for every file trail writes+ * for an agent: the commands as trail spells them (`graft check` became+ * `trail build --check`, see `cmd`), and the name in prose. The code map+ * still lives in `graft/`, so a `graft` followed by `/` is a path and stays,+ * as do `graft-…` and `graft_…` names.+ */+export function trailSpelling(text: string): string {+ return text+ .replace(/\bgraft (check|stats)\b(?![\w-])/g, (m) => cmd(m, "trail"))+ .replace(/\bGraft\b(?![/\w-])/g, "Trail")+ .replace(/\bgraft\b(?![/\w-])/g, "trail");+}++/**+ * The graft text with trail's spelling (see `trailSpelling`). Trail has its+ * own frontmatter and opens with the moments to reach for it. Then the parts+ * only trail has: learnings, corrections and the check before work goes for+ * review.*/function trailSkill(graft: string): string {- const text = graft- .replace(/^---\n[\s\S]*?\n---\n/, "")- .replace("### 6 · Lifecycle: \`graft build\` / \`graft check\`", "### 6 · Lifecycle: \`trail build\` / \`trail build --check\`")- .replace("\`check\` fails when \`graft/\` is stale, for CI.", "\`build --check\` fails when \`graft/\` is stale, for CI.")- .replace(/\bgraft\b(?![/\w-])/g, "trail")- .replace("# trail\n", `# trail\n\n${TRAIL_MOMENTS}`);+ const text = trailSpelling(+ graft+ .replace(/^---\n[\s\S]*?\n---\n/, "")+ .replace("\`check\` fails when \`graft/\` is stale, for CI.", "\`build --check\` fails when \`graft/\` is stale, for CI."),+ ).replace("# trail\n", `# trail\n\n${TRAIL_MOMENTS}`);return `---name: traildescription: ${TRAIL_DESCRIPTION}diff --git a/src/claude/tally.ts b/src/claude/tally.tsindex 93c77114..bdc4019e 100644--- a/src/claude/tally.ts+++ b/src/claude/tally.ts@@ -39,7 +39,7 @@ const TAIL_BYTES = 1024 * 1024;* whether the user was told. Anchored on "graft saved" + a number + "tokens" so* ordinary prose about graft can't trip it.*/-const TALLY = /graft\s+saved\s*[~≈]?\s*[\d,.]+\s*[km]?\s*(?:tok|tokens)/i;+const TALLY = /(?:graft|trail)\s+saved\s*[~≈]?\s*[\d,.]+\s*[km]?\s*(?:tok|tokens)/i;/** Did this reply tell the user what graft saved? */export function hasSavingsTally(text: string): boolean {diff --git a/src/cli-epilogue.ts b/src/cli-epilogue.tsindex b211951b..92e4494c 100644--- a/src/cli-epilogue.ts+++ b/src/cli-epilogue.ts@@ -4,6 +4,7 @@* so the exact text — spacing is hand-aligned, not incidental — can be* unit-tested without spawning the CLI.*/+import { brand, cmd } from "./brand.js";// The widest line (index 4, tied with index 2 at 26 chars) gets the live// node/edge stats appended, when a graph exists.@@ -52,8 +53,8 @@ export function formatInitEpilogue(opts: InitEpilogueOptions): string {}const steps: Step[] = [- ...(graphBuilt ? [] : [{ label: "build the graph", command: "graft build" }]),- { label: "restart your agent", command: "a new session picks up graft automatically" },+ ...(graphBuilt ? [] : [{ label: "build the graph", command: cmd("graft build") }]),+ { label: "restart your agent", command: `a new session picks up ${brand()} automatically` },{label: "code as usual",command: "ask your agent to fix a bug or explain a flow —",@@ -61,7 +62,7 @@ export function formatInitEpilogue(opts: InitEpilogueOptions): string {},{label: "explore by hand",- command: 'graft ask "where is auth handled?" · graft callers <fn> · graft viz',+ command: `${cmd("graft ask")} "where is auth handled?" · ${cmd("graft callers")} <fn> · ${cmd("graft viz")}`,},];@@ -79,7 +80,7 @@ export function formatInitEpilogue(opts: InitEpilogueOptions): string {}});- const closing = `${indent}share it: git add .claude && git commit — teammates run \`graft build\` for their own local graph`;+ const closing = `${indent}share it: git add .claude && git commit — teammates run \`${cmd("graft build")}\` for their own local graph`;return [...wordmark, "", ...stepLines, "", closing].join("\n");}diff --git a/src/cli-meta.ts b/src/cli-meta.tsindex add0ef0c..0d977c6b 100644--- a/src/cli-meta.ts+++ b/src/cli-meta.ts@@ -24,7 +24,7 @@ export function resolvePackageJsonPath(moduleUrl: string): string {}/**- * The npm package this code was installed as: `@trailhq/trail`, or+ * The npm package this code was installed as: `@trailhq/trail-code`, or* `@nanonets/graft` (the same code under its old name). Upgrades and update* checks go to the package actually installed, not to the name typed.*/diff --git a/src/cli-picker.ts b/src/cli-picker.tsindex 8ecd3db0..6cc3bcf9 100644--- a/src/cli-picker.ts+++ b/src/cli-picker.ts@@ -408,19 +408,20 @@ export async function runPicker(*/export function formatNonInteractiveHelp(detectedIds: string[]): string {const list = detectedIds.length > 0 ? detectedIds.join(", ") : "none";+ const b = brand();const examples: [string, string][] = [...(detectedIds.length > 0? ([- [`graft init --agents ${detectedIds.join(" ")}`, "wire these"],- ["graft init --yes", "same, without spelling them out"],+ [`${b} init --agents ${detectedIds.join(" ")}`, "wire these"],+ [`${b} init --yes`, "same, without spelling them out"],] as [string, string][]): []),- ["graft init --agents claude", "Claude Code only"],- ["graft init --dry-run", "list every file first"],+ [`${b} init --agents claude`, "Claude Code only"],+ [`${b} init --dry-run`, "list the agent wiring first"],];const width = Math.max(...examples.map(([cmd]) => cmd.length));return [- "graft init: no TTY to prompt on, and no --agents/--yes given — nothing written.",+ `${b} init: no TTY to prompt on, and no --agents/--yes given — nothing written.`,`detected: ${list}`,"",...examples.map(([cmd, note]) => ` ${cmd.padEnd(width)} # ${note}`),@@ -440,7 +441,9 @@ export function formatPlan(): string {const dim = tty ? muted : (s: string) => s;const warn = tty ? amber : (s: string) => s;- const writes = plan.filter((p) => ids.includes(p.id)).flatMap((p) => p.writes);+ // Codex, Hermes and Antigravity all write AGENTS.md: list each write once.+ const all = plan.filter((p) => ids.includes(p.id)).flatMap((p) => p.writes);+ const writes = [...new Map(all.map((w) => [`${w.path}\0${w.what}`, w])).values()];if (writes.length === 0) return 'would write — nothing (no agents selected)';const pad = (rows: PlannedWrite[], f: (p: string) => string) => {diff --git a/src/cli.ts b/src/cli.tsindex bfb50199..eb139797 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -24,7 +24,7 @@ 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 { brand, cmd, graftNotice, tag } from "./brand.js";+import { brand, cmd, graftNotice, strandedRepoNotice, tag } from "./brand.js";import { branchDiff } from "./cloud/diff.js";import { openBrowser } from "./util/browser.js";import { contextDirFor } from "./context/node-file.js";@@ -274,6 +274,10 @@ program.hook("preAction", (_parent, action) => {// hooks, CI and pipes never see it (see graftNotice).const renamed = graftNotice({ ran: spelling(action), tty: Boolean(process.stderr.isTTY) });if (renamed) console.error(renamed);+ // Someone typing trail in a repo whose graft-era hooks can't reach it learns+ // the one command that moves it (init itself is that command).+ const stranded = action.name() === "init" ? null : strandedRepoNotice({ cwd: process.cwd(), tty: Boolean(process.stderr.isTTY) });+ if (stranded) console.error(stranded);maybeRefreshInBackground();const nudge = formatUpdateNudge(currentVersion, readUpdateCache()?.latest);if (nudge) console.error(nudge);@@ -1719,6 +1723,7 @@ function wireTarget(mcp: opts.mcp,hooks: opts.hooks,global: opts.global,+ brand: brand(),});for (const w of r.written) say(`✓ ${w.id}: ${w.path} (${w.action})`);for (const m of r.mcp) say(`✓ mcp ${m.id}: ${m.path} (${m.action})`);diff --git a/src/cloud/nudge.ts b/src/cloud/nudge.tsindex 51d4ae81..5e25932a 100644--- a/src/cloud/nudge.ts+++ b/src/cloud/nudge.ts@@ -29,7 +29,7 @@ import { durationBucket } from "../telemetry/contract.js";import { track } from "../telemetry/track.js";import { readJson, writeJsonAtomic } from "../util/state.js";import { claimHandoff, readCloud, registerHandoff, SECRET_FILE_MODE, trailUrl, writeCloud, type ClaimResult, type HandoffRepo } from "./workspace.js";-import { syncWorkspaceRepos } from "./workspace-sync.js";+import { dropActivity, syncWorkspaceRepos } from "./workspace-sync.js";/** What the link says, in turn: one per session, so it never reads the same twice running. */export const NUDGE_WORDS = ["Share your learnings with your team?", "See what your Claude has learned"] as const;@@ -285,6 +285,9 @@ export async function waitForConnect(opts: WaitOptions = {}): Promise<ClaimResulconst got = await claimHandoff(base, pending.state, opts.fetchImpl);if ("cloud" in got) {const cloud = { ...got.cloud, url: base, linkedAt: now() };+ // Nothing from before signing in goes up: an older trail queued uses+ // whether or not anyone had connected.+ dropActivity(env);writeCloud(cloud, env);const sent = await syncWorkspaceRepos(cloud, opts.fetchImpl);done({ pending: undefined, linked: { workspace: cloud.workspace.name, url: cloud.workspace.url, repos: sent.repos, learnings: sent.learnings } });diff --git a/src/cloud/workspace-sync.ts b/src/cloud/workspace-sync.tsindex bb59caa8..d1a0d4aa 100644--- a/src/cloud/workspace-sync.ts+++ b/src/cloud/workspace-sync.ts@@ -8,10 +8,11 @@* repo. Personal learnings in ~/.trail never go up.** Uses (a search that showed learnings, a check against them) are appended to- * `~/.trail/outbox.jsonl` as they happen, whether or not the machine is- * connected yet, and sent with the next sync. That's how a teammate's reuse- * of a learning shows on the team page, including reuse from before they- * connected.+ * `~/.trail/outbox.jsonl` as they happen, and sent with the next sync. That's+ * how a teammate's reuse of a learning shows on the team page. Only while the+ * machine is connected, and only for a repo in the workspace: a search holds+ * what someone typed and the files they're in, and nobody agreed to send that+ * for a repo they didn't pick, or from before they signed in.** Commands never wait on any of this: when something changed, a detached* `_trail-sync` child does it.@@ -133,12 +134,22 @@ export async function syncWorkspaceRepos(cloud: Cloud, fetchImpl?: typeof fetch)/* the activity outbox *//* -------------------------------------------------------------------------- */-function outboxPath(): string {- return join(trailHome(), "outbox.jsonl");+function outboxPath(env: NodeJS.ProcessEnv = process.env): string {+ return join(trailHome(env), "outbox.jsonl");}-/** Remember one use of the learnings, to send with the next sync. Never throws. */-export function recordActivity(e: ActivityEvent): void {+/** Whether a use may go to `cloud`: the repo is the workspace's, and it happened since connecting. */+function sendable(e: ActivityEvent, cloud: Cloud): boolean {+ return cloud.repos.includes(e.repo) && Date.parse(e.at) >= (cloud.linkedAt || 0);+}++/**+ * Remember one use of the learnings, to send with the next sync: only while+ * this machine is connected, and only for a repo in the workspace. Not+ * connected, or another repo, and nothing is written. Never throws.+ */+export function recordActivity(e: ActivityEvent, cloud: Cloud | null = readCloud()): void {+ if (!cloud || !cloud.repos.includes(e.repo)) return;try {const p = outboxPath();appendFileSync(p, `${JSON.stringify(e)}\n`);@@ -151,6 +162,18 @@ export function recordActivity(e: ActivityEvent): void {}}+/**+ * Forget every use waiting to go. Run when a machine connects, so nothing+ * recorded before that is ever sent.+ */+export function dropActivity(env: NodeJS.ProcessEnv = process.env): void {+ try {+ rmSync(outboxPath(env), { force: true });+ } catch {+ /* sent-time filtering in flushActivity drops them anyway */+ }+}+function outboxHasEvents(): boolean {try {return statSync(outboxPath()).size > 0;@@ -161,7 +184,9 @@ function outboxHasEvents(): boolean {/*** Send the outbox. It's moved aside first, so events recorded while the- * request is out land in a fresh file; on failure they're put back.+ * request is out land in a fresh file; on failure they're put back. A use+ * from before this connection, or for a repo the workspace doesn't have+ * (left by an older trail), is dropped, never sent.*/export async function flushActivity(cloud: Cloud, fetchImpl?: typeof fetch): Promise<number> {const p = outboxPath();@@ -175,7 +200,9 @@ export async function flushActivity(cloud: Cloud, fetchImpl?: typeof fetch): Proconst events: ActivityEvent[] = [];for (const line of readFileSync(sending, "utf8").split("\n")) {try {- if (line.trim()) events.push(JSON.parse(line) as ActivityEvent);+ if (!line.trim()) continue;+ const e = JSON.parse(line) as ActivityEvent;+ if (sendable(e, cloud)) events.push(e);} catch {/* a torn line */}diff --git a/src/context/check.ts b/src/context/check.tsindex 1fd4686f..03052158 100644--- a/src/context/check.ts+++ b/src/context/check.ts@@ -19,7 +19,7 @@ import { relPosix } from "../util/paths.js";import { readSourceFile } from "../util/source.js";import { CODE_EXTENSIONS, listContextFiles } from "./build.js";import { contextDirFor, readManifest, readNodes } from "./node-file.js";-import { cmd } from "../brand.js";+import { brand, cmd } from "../brand.js";export interface CheckResult {ok: boolean;@@ -146,9 +146,9 @@ export function indexFreshness(dir: string, opts: CheckOptions = {}): FreshnessRexport function staleBanner(f: FreshnessResult | null): string | null {if (!f || f.missing === 0) return null;return (- `⚠ graft's index may be ahead of your working tree: ${f.missing} of ${f.total} indexed ` +- `files are not on disk (branch switch or uncommitted move?). If graft names a path that ` +- `isn't there, don't chase it — \`graft grep\` the symbol to find where it lives now; run \`graft build\` to refresh.`+ `⚠ ${brand()}'s index may be ahead of your working tree: ${f.missing} of ${f.total} indexed ` ++ `files are not on disk (branch switch or uncommitted move?). If ${brand()} names a path that ` ++ `isn't there, don't chase it — \`${cmd("graft grep")}\` the symbol to find where it lives now; run \`${cmd("graft build")}\` to refresh.`);}diff --git a/src/context/savings.ts b/src/context/savings.tsindex 475a4425..75c3daf9 100644--- a/src/context/savings.ts+++ b/src/context/savings.ts@@ -90,11 +90,12 @@ export function setInputRate(usdPerMtok: number | null): void {* `hasSavingsTally` (claude/tally.ts) recognises, so adding money here does not* quietly zero the reported-turns metric. */export function savingsTurnNudge(savedTokens: number): string {- const sum = ' — sum each such line across your graft calls — e.g. ';+ const b = brand();+ const sum = ` — sum each such line across your ${b} calls — e.g. `;if (inputRateUsdPerMtok === null || savedTokens <= 0) {return (- ' At the end of your reply, tell the user the total graft tokens saved ' +- `this turn${sum}"🌱 graft saved ~N tokens this turn".`+ ` At the end of your reply, tell the user the total ${b} tokens saved ` ++ `this turn${sum}"🌱 ${b} saved ~N tokens this turn".`);}const usd = (savedTokens * inputRateUsdPerMtok) / 1_000_000;diff --git a/src/graph/cards.ts b/src/graph/cards.tsindex 4afdb5d4..7d5cbb9d 100644--- a/src/graph/cards.ts+++ b/src/graph/cards.ts@@ -21,6 +21,7 @@ import { matter } from "../util/front-matter.js";import type { GraphV1, NodeV1 } from "./types.js";import { CACHE_DIR, readNodes } from "../context/node-file.js";import { GRAPH_DIR } from "./write.js";+import { inBrand } from "../brand.js";const INDEX_FILE = "INDEX.md";/** Where a root-level file card goes when `graft/<stem>.md` is already a concept@@ -208,6 +209,7 @@ export function writeCards(graph: GraphV1, outDir: string): CardStats {* nodes on disk and the per-file cards. Deterministic order; no timestamps.*/export function writeIndex(outDir: string, files: CardFileInfo[]): void {+ // Spelled by the name that built it: a trail-only machine has no `graft` to run.const lines: string[] = ["# graft — repo map","",@@ -223,7 +225,7 @@ export function writeIndex(outDir: string, files: CardFileInfo[]): void {"as the `graft` CLI everywhere else. Edges — who calls what — live only in the","graph, not in these files: `graft callers <symbol>` is the only way to read them.","",- ];+ ].map((l) => inBrand(l));const concepts = readNodes(outDir).sort((a, b) => a.slug.localeCompare(b.slug));if (concepts.length) {diff --git a/src/graph/traverse-cli.ts b/src/graph/traverse-cli.tsindex a378d0a2..d1466ea8 100644--- a/src/graph/traverse-cli.ts+++ b/src/graph/traverse-cli.ts@@ -18,6 +18,7 @@ import { withSavings, savingsFor, type Savings } from "../context/savings.js";import { loadGraphCached } from "./load.js";import { resolveSymbol, edgeWalk, type Direction, type EdgeHit } from "./traverse.js";import type { GraphV1, NodeV1 } from "./types.js";+import { cmd } from "../brand.js";export interface CallersCliOptions {in?: string;@@ -107,7 +108,7 @@ export function looseNoteFor(direction: Direction, name: string, candidateCount:candidateCount > 1? ` ${candidateCount} definitions share the name "${name}"; a cross-file caller of an ambiguous name is dropped rather than guessed, so this may undercount.`: "";- return ` no indexed ${label} — the graph has no ${dir} call/reference edges for this symbol as written.${ambiguity} Check the name (try the bare symbol, or "Type.method"), or find its uses with graft grep "${name}". Fall back to raw grep -rn only for unindexed files`;+ return ` no indexed ${label} — the graph has no ${dir} call/reference edges for this symbol as written.${ambiguity} Check the name (try the bare symbol, or "Type.method"), or find its uses with ${cmd("graft grep")} "${name}". Fall back to raw grep -rn only for unindexed files`;}interface SymbolJson {@@ -168,7 +169,7 @@ export function runCallersCommand(query: string, dir: string, opts: CallersCliOpconst contextDir = contextDirFor(root, opts.globalDir);const graph = loadGraphCached(contextDir);if (!graph) {- console.error(`✗ no graph found at ${contextDir} — run \`graft build\` first`);+ console.error(`✗ no graph found at ${contextDir} — run \`${cmd("graft build")}\` first`);process.exit(1);}@@ -184,7 +185,7 @@ export function runCallersCommand(query: string, dir: string, opts: CallersCliOpreturn;}if (matches.length === 0) {- console.error(`✗ no symbol "${query}" in the graph — check spelling or run graft build`);+ console.error(`✗ no symbol "${query}" in the graph — check spelling or run ${cmd("graft build")}`);process.exit(1);}diff --git a/src/graph/workspace-cli.ts b/src/graph/workspace-cli.tsindex 7fb1296b..09755639 100644--- a/src/graph/workspace-cli.ts+++ b/src/graph/workspace-cli.ts@@ -8,7 +8,7 @@import { Graft } from "../engine.js";import { contextDirFor, ensureGitignored } from "../context/node-file.js";import { patchBuildConfig, type BuildConfig } from "../util/state.js";-import { brand, PACKAGE_FOR } from "../brand.js";+import { brand, cmd, PACKAGE_FOR } from "../brand.js";import { nativeFallbackNotice } from "./native.js";import type { EngineConfig } from "../ai/providers.js";import { formatAsk } from "../ask/ask.js";@@ -91,7 +91,7 @@ export async function runWorkspaceBuild(root: string, opts: WorkspaceBuildOption// index (graft/workspace.json) is written outside buildGraph, so ignore it here too.ensureGitignored(root, contextDirFor(root, opts.override));console.log(`✓ workspace: ${children.length} repos federated → graft/workspace.json`);- console.log(` graft/ is git-ignored — each teammate runs \`graft build\` to regenerate it locally.`);+ console.log(` graft/ is git-ignored — each teammate runs \`${cmd("graft build")}\` to regenerate it locally.`);const notice = nativeFallbackNotice({ languages: [...fellBack.languages].sort(), packages: [...fellBack.packages].sort() },opts.packageName ?? PACKAGE_FOR[brand()],diff --git a/src/graph/workspace.ts b/src/graph/workspace.tsindex d371586f..13c8a043 100644--- a/src/graph/workspace.ts+++ b/src/graph/workspace.ts@@ -51,6 +51,7 @@ import { fuseScopes, STRONG_FLOOR, HIGH_FLOOR, type ScopedDoc } from "../ask/fusimport { grepGraph, type GrepGroup, type GrepResult } from "../search/grep.js";import { formatGrepResult, zeroHitNote } from "../search/grep-cli.js";import { withSavings, type Savings } from "../context/savings.js";+import { cmd } from "../brand.js";/** The parent index written to `<parent>/graft/workspace.json`. Nodes/edges* never live at the parent — they live in each child's own `graft/`. */@@ -161,7 +162,7 @@ export function loadWorkspaceGraphs(root: string, override?: string): WorkspaceGexport function coverageNote(g: WorkspaceGraphs): string {if (g.missing.length === 0) return "";const total = g.loaded.length + g.missing.length;- return `${g.loaded.length} of ${total} workspace repos have graphs; run graft build to cover ${g.missing.join(", ")}`;+ return `${g.loaded.length} of ${total} workspace repos have graphs; run ${cmd("graft build")} to cover ${g.missing.join(", ")}`;}/** Prefix a hit pointer with its child dir so a `path:span` (or concept path@@ -504,7 +505,7 @@ export function federateAsk(alsoMatched: unmatched.filter((match) => !federatedSet.has(match.scope)),};} else {- result.note = `no matching nodes across ${wg.loaded.length} workspace repo(s) — try different words, or \`graft build\` at a child`;+ result.note = `no matching nodes across ${wg.loaded.length} workspace repo(s) — try different words, or \`${cmd("graft build")}\` at a child`;}if (note) result.note = result.note ? `${result.note}\n${note}` : note;return result;@@ -551,7 +552,7 @@ export function federateAsk(const federated = fused.federated.length ? fused.federated : [...new Set(hits.map((h) => h.scope!))];result.scopes = { federated, alsoMatched };} else {- result.note = `no matching nodes across ${wg.loaded.length} workspace repo(s) — try different words, or \`graft build\` at a child`;+ result.note = `no matching nodes across ${wg.loaded.length} workspace repo(s) — try different words, or \`${cmd("graft build")}\` at a child`;}if (note) result.note = result.note ? `${result.note}\n${note}` : note;return result;@@ -648,7 +649,7 @@ export async function federateCheck(lines.push(`${child}/: STALE (${bits.join(", ")})`);}}- for (const child of wg.missing) lines.push(`${child}/: not built (run graft build)`);+ for (const child of wg.missing) lines.push(`${child}/: not built (run ${cmd("graft build")})`);const cov = coverageNote(wg);if (cov) lines.push("", cov);return { text: lines.join("\n") + "\n", ok };@@ -686,7 +687,7 @@ export function federateCallers(const cov = coverageNote(wg);if (!found) {- const base = `no symbol "${symbol}" in any of the ${wg.loaded.length} workspace repo(s) — check spelling or run graft build`;+ const base = `no symbol "${symbol}" in any of the ${wg.loaded.length} workspace repo(s) — check spelling or run ${cmd("graft build")}`;return { text: cov ? `${base}\n${cov}` : base, found: false };}let text = blocks.join("\n\n");diff --git a/src/hosts/antigravity.ts b/src/hosts/antigravity.tsindex 5fc2da05..ba39e0ce 100644--- a/src/hosts/antigravity.ts+++ b/src/hosts/antigravity.ts@@ -10,32 +10,47 @@* `antigravitySkillTargets()` is the pure "which files would this touch" half (for* `graft init --dry-run` / the picker); `installAntigravitySkill()` does the write.*/-import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';+import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, rmdirSync } from 'node:fs';import { dirname, join } from 'node:path';import { skillTemplate } from '../claude/skill-template.js';import type { PlannedWrite } from './plan.js';import type { ConfigWrite } from './config-write.js';+import type { Brand } from '../brand.js';/** The skill file path, under the user's global Antigravity skills dir. */-function skillPath(home: string): string {- return join(home, '.gemini', 'skills', 'graft', 'SKILL.md');+function skillPath(home: string, name: Brand = 'graft'): string {+ return join(home, '.gemini', 'skills', name, 'SKILL.md');}/** The files installing Antigravity's global skill would touch — pure, no writes. */-export function antigravitySkillTargets(home: string): PlannedWrite[] {+export function antigravitySkillTargets(home: string, name: Brand = 'graft'): PlannedWrite[] {return [{hostId: 'antigravity', id: 'antigravity-skill',- path: skillPath(home),- scope: 'global', kind: 'skill', what: 'graft skill (shared)',+ path: skillPath(home, name),+ scope: 'global', kind: 'skill', what: `${name} skill (shared)`,},];}-/** Write graft's skill into `~/.gemini/skills/graft/SKILL.md`, idempotently. */-export function installAntigravitySkill(home: string): ConfigWrite[] {- const path = skillPath(home);- const content = skillTemplate();+/**+ * Write the skill into `~/.gemini/skills/graft/SKILL.md`, idempotently; under+ * trail into `skills/trail/`, in trail's text, and graft's copy goes so the+ * agent doesn't load two. Every workspace reads this one, so once trail's is+ * there a repo still on graft leaves it, rather than add graft's back beside+ * it; trail's text says what to run when only graft is installed.+ */+export function installAntigravitySkill(home: string, name: Brand = 'graft'): ConfigWrite[] {+ if (name === 'graft' && existsSync(skillPath(home, 'trail'))) {+ return [{ id: 'antigravity-skill', path: skillPath(home, 'trail'), action: 'unchanged' }];+ }+ if (name === 'trail') {+ const old = skillPath(home, 'graft');+ rmSync(old, { force: true });+ try { rmdirSync(dirname(old)); } catch { /* not empty, or not there */ }+ }+ const path = skillPath(home, name);+ const content = skillTemplate(name);const existed = existsSync(path);if (existed && readFileSync(path, 'utf8') === content) {return [{ id: 'antigravity-skill', path, action: 'unchanged' }];diff --git a/src/hosts/cursor-hooks.ts b/src/hosts/cursor-hooks.tsindex b967519c..1ce783e4 100644--- a/src/hosts/cursor-hooks.ts+++ b/src/hosts/cursor-hooks.ts@@ -22,17 +22,20 @@* - `afterMCPExecution` → the graft MCP calls, savings parsed from `result_json`.* - `sessionEnd` → roll the closed session up into `session_summary` as Cursor.*/-import { writeFileSync } from 'node:fs';+import { rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { hooksShim } from '../claude/shim-template.js';import type { PlannedWrite } from './plan.js';import { writeOwned, isGraftEntry, readJsonObject, type ConfigWrite } from './config-write.js';+import { cursorHookShimRelPath } from './registry.js';+import type { Brand } from '../brand.js';/** The Cursor hooks.json schema version graft writes. */const CURSOR_HOOKS_VERSION = 1;-function shimPathFor(repo: string): string {- return join(repo, '.cursor', 'hooks', 'graft-hooks.cjs');+/** `.cursor/hooks/graft-hooks.cjs`, or `trail-hooks.cjs` in a repo that uses trail. */+export function shimPathFor(repo: string, name: Brand = 'graft'): string {+ return join(repo, cursorHookShimRelPath(name));}function configPathFor(repo: string): string {return join(repo, '.cursor', 'hooks.json');@@ -44,11 +47,11 @@ function configPathFor(repo: string): string {* the Cursor-only, no-global init). Always returns the pair: unlike Codex there* is no "is the CLI installed" gate — the repo's own `.cursor/` is what we write.*/-export function cursorHookTargets(repo: string): PlannedWrite[] {+export function cursorHookTargets(repo: string, name: Brand = 'graft'): PlannedWrite[] {return [{hostId: 'cursor', id: 'cursor-hook-shim',- path: shimPathFor(repo),+ path: shimPathFor(repo, name),scope: 'repo', kind: 'hook', what: 'session-scoring hook shim',},{@@ -80,9 +83,12 @@ function desiredEntries(): DesiredEntry[] {* clobbered. Foreign hook entries are preserved; a stale graft entry is replaced* so an upgrade re-points to the current shim/sub-command instead of stacking.*/-export function installCursorHooks(repo: string): ConfigWrite[] {- const shimPath = shimPathFor(repo);+export function installCursorHooks(repo: string, name: Brand = 'graft'): ConfigWrite[] {+ const shimPath = shimPathFor(repo, name);const shimWrite = writeOwned('cursor-hook-shim', shimPath, hooksShim(), 0o755);+ // A repo moving to trail's names: graft's shim goes, and its entries are+ // replaced below (`isGraftEntry` knows both names).+ if (name === 'trail') rmSync(shimPathFor(repo, 'graft'), { force: true });const cfgPath = configPathFor(repo);const skipped: ConfigWrite = { id: 'cursor-hooks', path: cfgPath, action: 'skipped-unparseable' };diff --git a/src/hosts/init.ts b/src/hosts/init.tsindex c62c06d4..36f2c4ba 100644--- a/src/hosts/init.ts+++ b/src/hosts/init.ts@@ -3,11 +3,12 @@* Selection = explicit ids > all > detected. Claude Code is handled* separately by src/claude/init.ts (hooks + statusline + skill).*/-import { statSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'node:fs';-import { dirname, join } from 'node:path';+import { statSync, writeFileSync, readFileSync, mkdirSync, existsSync, rmSync, rmdirSync } from 'node:fs';+import { basename, dirname, join } from 'node:path';import { homedir } from 'node:os';-import { HOSTS, detectHosts, type DetectProbe, type HostTarget } from './registry.js';-import { upsertSection } from './sections.js';+import { HOSTS, detectHosts, hostRelPath, hostWiringName, type DetectProbe, type HostTarget } from './registry.js';+import { GRAFT_MARKERS, markersFor, upsertSection } from './sections.js';+import type { Brand } from '../brand.js';import { registerMcpConfigs, type McpWrite } from './mcp-config.js';import { installCodexHooks } from './codex-hooks.js';import { installCursorHooks } from './cursor-hooks.js';@@ -38,6 +39,17 @@ function writeOwned(path: string, content: string): string {return existed ? 'replaced' : 'created';}+/**+ * A graft-named file a host owned, gone now that the repo uses trail's names,+ * with its `graft/` folder when that was all the folder held.+ */+function removeGraftCopy(path: string): void {+ rmSync(path, { force: true });+ if (basename(dirname(path)) === 'graft') {+ try { rmdirSync(dirname(path)); } catch { /* not empty, or not there */ }+ }+}+export function runHostsInit(repo: string,opts: {@@ -48,10 +60,13 @@ export function runHostsInit(hooks?: boolean;/** false → skip every write outside the repo (the ~/.codex/ targets). */global?: boolean;+ /** The name `init` runs under; trail's moves the repo to trail's names (see `hostWiringName`). */+ brand?: Brand;} = {},): HostsInitResult {const home = opts.home ?? homedir();const probe = probeFor(home, repo);+ const name = hostWiringName(repo, opts.brand);let selected: HostTarget[];let unknown: string[] = [];@@ -67,18 +82,21 @@ export function runHostsInit(const written: HostsInitResult['written'] = [];for (const host of selected) {- const path = join(repo, host.relPath);+ const path = join(repo, hostRelPath(host, name));+ // Under trail, graft's copy of an owned file goes and graft's fenced+ // block becomes trail's, so the agent reads the instructions once.const action =host.kind === 'owned'- ? writeOwned(path, host.content())- : upsertSection(path, host.content()).action;+ ? writeOwned(path, host.content(name))+ : upsertSection(path, host.content(name), markersFor(name), name === 'trail' ? [GRAFT_MARKERS] : []).action;+ if (name === 'trail' && host.kind === 'owned') removeGraftCopy(join(repo, host.relPath));written.push({ id: host.id, path, action });}const skipped = HOSTS.filter((h) => !selected.includes(h)).map((h) => h.id);const mcp =opts.mcp === false? []- : registerMcpConfigs(repo, selected.map((h) => h.id), { home, global: opts.global });+ : registerMcpConfigs(repo, selected.map((h) => h.id), { home, global: opts.global, name });// The Codex hook targets are user-level (~/.codex), so --no-global suppresses them.const hooks =opts.hooks === false || opts.global === false || !selected.some((h) => h.id === 'agents')@@ -89,13 +107,13 @@ export function runHostsInit(const cursorHooks =opts.hooks === false || !selected.some((h) => h.id === 'cursor')? []- : installCursorHooks(repo);+ : installCursorHooks(repo, name);// Both write the hooks shim, which finds this install through the trail home.if (hooks.length > 0 || cursorHooks.length > 0) rememberInstall(home);// Antigravity's skill is a global write too, so --no-global suppresses it as well.const antigravitySkill =opts.global === false || !selected.some((h) => h.id === 'antigravity')? []- : installAntigravitySkill(home);+ : installAntigravitySkill(home, name);return { written, skipped, unknown, mcp, hooks: [...hooks, ...cursorHooks, ...antigravitySkill] };}diff --git a/src/hosts/instructions.ts b/src/hosts/instructions.tsindex 417c37ed..ebce6fa4 100644--- a/src/hosts/instructions.ts+++ b/src/hosts/instructions.ts@@ -1,9 +1,23 @@/*** The one canonical Graft instruction block, rendered into each host's* native format. Content changes happen HERE only; renderers just wrap it.+ *+ * `name` is the repo's name for the tool (see `hostWiringName`): a repo wired+ * by trail gets the same text in trail's spelling, so an agent on a machine+ * with only `trail` installed is never told to run `graft`.*/+import type { Brand } from '../brand.js';+import { trailSpelling } from '../claude/skill-template.js';-export function instructionBody(): string {+function inName(text: string, name: Brand): string {+ return name === 'trail' ? trailSpelling(text) : text;+}++export function instructionBody(name: Brand = 'graft'): string {+ return inName(graftBody(), name);+}++function graftBody(): string {return `## Graft — repo context graphThis repo is indexed in \`graft/\`: small linked markdown nodes that explain each@@ -45,24 +59,24 @@ After big code changes, refresh the graph with \`graft build\` (deterministic,no API key, $0).`;}-export function cursorRule(): string {- return `---+export function cursorRule(name: Brand = 'graft'): string {+ return inName(`---description: Use the Graft context graph in graft/ before exploring sourcealwaysApply: true----${instructionBody()}-`;+${graftBody()}+`, name);}-export function kiroSteering(): string {- return `---+export function kiroSteering(name: Brand = 'graft'): string {+ return inName(`---inclusion: always----${instructionBody()}-`;+${graftBody()}+`, name);}-export function windsurfRule(): string {- return `${instructionBody()}-`;+export function windsurfRule(name: Brand = 'graft'): string {+ return inName(`${graftBody()}+`, name);}diff --git a/src/hosts/mcp-config.ts b/src/hosts/mcp-config.tsindex e0ee7592..cf53817b 100644--- a/src/hosts/mcp-config.ts+++ b/src/hosts/mcp-config.ts@@ -13,7 +13,7 @@ import { dirname, join } from 'node:path';import { homedir } from 'node:os';import type { PlannedWrite } from './plan.js';import { readJsonObject, type ConfigWrite } from './config-write.js';-import { trailOnPath } from '../brand.js';+import { trailOnPath, type Brand } from '../brand.js';/** MCP registration reports the same write-result record every installer does. */export type McpWrite = ConfigWrite;@@ -23,8 +23,10 @@ export interface McpTarget extends PlannedWrite {format: 'json' | 'toml';/** JSON only: the top-level key holding the server map. */topKey?: string;- /** JSON only: the server entry to merge in under `graft`. */+ /** JSON only: the server entry to merge in under `key`. */entry?: object;+ /** The server's name in the file: `graft`, or `trail` in a repo that uses trail. */+ key: Brand;}/**@@ -48,7 +50,7 @@ const NPX_LAUNCH = { command: 'npx', args: ['-y', '@nanonets/graft', 'mcp'] };const BIN_LAUNCH = { command: 'graft', args: ['mcp'] };// The same server under trail's name, for a repo that uses trail: its tools are// `trail_*` (and it still answers `graft_*`).-const TRAIL_NPX_LAUNCH = { command: 'npx', args: ['-y', '@trailhq/trail', 'mcp'] };+const TRAIL_NPX_LAUNCH = { command: 'npx', args: ['-y', '@trailhq/trail-code', 'mcp'] };const TRAIL_BIN_LAUNCH = { command: 'trail', args: ['mcp'] };function graftOnPath(): boolean {@@ -73,8 +75,8 @@ export function serverEntry(opts: { onPath?: boolean; brand?: 'graft' | 'trail'}-function opencodeEntry(): object {- const { command, args } = serverEntry();+function opencodeEntry(name: Brand = 'graft'): object {+ const { command, args } = serverEntry({ brand: name });return { type: 'local', command: [command, ...args], enabled: true };}@@ -105,20 +107,23 @@ export function mergeJsonKey(id: string, path: string, topKey: string, entry: obreturn { id, path, action };}-/** The `[mcp_servers.graft]` table header, as written and as matched. */-const TOML_HEADER = '[mcp_servers.graft]';+/** The `[mcp_servers.graft]` (or `.trail`) table header, as written and as matched. */+function tomlHeader(name: Brand): string {+ return `[mcp_servers.${name}]`;+}/**- * Remove the `[mcp_servers.graft]` table from a TOML config, returning the rest.+ * Remove the `[mcp_servers.graft]` table (or `name`'s) from a TOML config, returning the rest.** Line-based on purpose: a real parse-and-reserialize would reformat the user's* whole file. The table runs from its header to the next `[`-header or EOF, which* is exactly the shape {@link upsertCodexToml} appends. Exported so the writer and* `retract.ts` can never disagree about what "graft's section" means.*/-export function stripTomlSection(text: string): { rest: string; found: boolean } {+export function stripTomlSection(text: string, name: Brand = 'graft'): { rest: string; found: boolean } {const lines = text.split('\n');- const start = lines.findIndex((l) => l.trim() === TOML_HEADER);+ const header = tomlHeader(name);+ const start = lines.findIndex((l) => l.trim() === header);if (start === -1) return { rest: text, found: false };let end = start + 1;while (end < lines.length && !lines[end].trimStart().startsWith('[')) end++;@@ -138,14 +143,17 @@ export function stripTomlSection(text: string): { rest: string; found: boolean }* and re-append instead, so this converges like every other writer — foreign* tables are untouched either way.*/-function upsertCodexToml(id: string, path: string): McpWrite {+function upsertCodexToml(id: string, path: string, name: Brand = 'graft'): McpWrite {const existed = existsSync(path);const text = existed ? readFileSync(path, 'utf8') : '';- const { command, args } = serverEntry();+ const { command, args } = serverEntry({ brand: name });const argList = args.map((a) => JSON.stringify(a)).join(", ");- const section = `${TOML_HEADER}\ncommand = \"${command}\"\nargs = [${argList}]\n`;+ const section = `${tomlHeader(name)}\ncommand = \"${command}\"\nargs = [${argList}]\n`;- const { rest, found } = stripTomlSection(text);+ const own = stripTomlSection(text, name);+ // Under trail, graft's table goes: the same server, listed once.+ const { rest, found: oldFound } = name === 'trail' ? stripTomlSection(own.rest, 'graft') : { rest: own.rest, found: false };+ const found = own.found && !oldFound;// Byte-identical already: don't rewrite the file just to reorder it.if (found && text === appendSection(rest, section)) return { id, path, action: 'unchanged' };@@ -168,30 +176,38 @@ function jsonTarget(topKey: string,entry: object,scope: PlannedWrite['scope'] = 'repo',+ key: Brand = 'graft',): McpTarget {- return { hostId, id, path, scope, kind: 'mcp', what: `${topKey}.graft`, format: 'json', topKey, entry };+ return { hostId, id, path, scope, kind: 'mcp', what: `${topKey}.${key}`, format: 'json', topKey, entry, key };}/*** The MCP config files selecting these hosts would touch — pure, no writes.* Codex's target is the user-level `~/.codex/config.toml`, so it is scoped* 'global': registering there affects every project on the machine.+ *+ * `name` is the repo's name for the tool: under trail the server is `trail`,+ * launched as `trail mcp` (or `npx -y @trailhq/trail-code mcp`). The files+ * are the same either way.*/export function mcpTargets(repo: string,ids: string[],- opts: { home?: string } = {},+ opts: { home?: string; name?: Brand } = {},): McpTarget[] {const home = opts.home ?? homedir();- const entry = serverEntry();+ const name = opts.name ?? 'graft';+ const entry = serverEntry({ brand: name });+ const json = (hostId: string, id: string, path: string, topKey: string, e: object, scope: PlannedWrite['scope'] = 'repo') =>+ jsonTarget(hostId, id, path, topKey, e, scope, name);const out: McpTarget[] = [];for (const id of ids) {switch (id) {case 'cursor':- out.push(jsonTarget(id, id, join(repo, '.cursor', 'mcp.json'), 'mcpServers', entry));+ out.push(json(id, id, join(repo, '.cursor', 'mcp.json'), 'mcpServers', entry));break;case 'gemini':- out.push(jsonTarget(id, id, join(repo, '.gemini', 'settings.json'), 'mcpServers', entry));+ out.push(json(id, id, join(repo, '.gemini', 'settings.json'), 'mcpServers', entry));break;case 'antigravity':// Antigravity reads MCP from its OWN registry, separate from Gemini CLI's@@ -199,18 +215,18 @@ export function mcpTargets(// gap #62 reported). Standard `{command,args}` under `mcpServers`. Global// scope: it applies to every workspace opened in Antigravity.out.push(- jsonTarget(id, 'antigravity', join(home, '.gemini', 'config', 'mcp_config.json'), 'mcpServers', entry, 'global'),+ json(id, 'antigravity', join(home, '.gemini', 'config', 'mcp_config.json'), 'mcpServers', entry, 'global'),);break;case 'kiro':- out.push(jsonTarget(id, id, join(repo, '.kiro', 'settings', 'mcp.json'), 'mcpServers', entry));+ out.push(json(id, id, join(repo, '.kiro', 'settings', 'mcp.json'), 'mcpServers', entry));break;case 'grok':// Grok reads MCP from repo-level `.grok/config.toml` (`[mcp_servers.<name>]`),// the same TOML shape Codex uses at ~/.codex/config.toml.out.push({hostId: id, id: 'grok', path: join(repo, '.grok', 'config.toml'),- scope: 'repo', kind: 'mcp', what: '[mcp_servers.graft]', format: 'toml',+ scope: 'repo', kind: 'mcp', what: tomlHeader(name), format: 'toml', key: name,});break;case 'agents':@@ -219,11 +235,11 @@ export function mcpTargets(if (dirExists(join(home, '.codex'))) {out.push({hostId: id, id: 'codex', path: join(home, '.codex', 'config.toml'),- scope: 'global', kind: 'mcp', what: '[mcp_servers.graft]', format: 'toml',+ scope: 'global', kind: 'mcp', what: tomlHeader(name), format: 'toml', key: name,});}if (dirExists(join(home, '.config', 'opencode'))) {- out.push(jsonTarget(id, 'opencode', join(repo, 'opencode.json'), 'mcp', opencodeEntry()));+ out.push(json(id, 'opencode', join(repo, 'opencode.json'), 'mcp', opencodeEntry(name)));}break;default:@@ -233,16 +249,36 @@ export function mcpTargets(return out;}+/**+ * Whether a machine-wide config already runs the server under trail's name.+ * Every repo on the machine reads it, and `trail mcp` serves a repo still on+ * graft too, so a graft repo leaves it alone rather than list the server twice.+ */+function trailServerIn(t: McpTarget): boolean {+ if (t.format === 'toml') {+ try {+ return stripTomlSection(readFileSync(t.path, 'utf8'), 'trail').found;+ } catch {+ return false;+ }+ }+ const loaded = readJsonObject(t.path);+ const bucket = loaded === 'unparseable' ? undefined : loaded.root[t.topKey!];+ return typeof bucket === 'object' && bucket !== null && !Array.isArray(bucket) && 'trail' in bucket;+}+export function registerMcpConfigs(repo: string,ids: string[],- opts: { home?: string; global?: boolean } = {},+ opts: { home?: string; global?: boolean; name?: Brand } = {},): McpWrite[] {+ const name = opts.name ?? 'graft';return mcpTargets(repo, ids, opts).filter((t) => opts.global !== false || t.scope !== 'global')- .map((t) =>- t.format === 'toml'- ? upsertCodexToml(t.id, t.path)- : mergeJsonKey(t.id, t.path, t.topKey!, t.entry!),- );+ .map((t) => {+ if (name === 'graft' && t.scope === 'global' && trailServerIn(t)) return { id: t.id, path: t.path, action: 'unchanged' as const };+ return t.format === 'toml'+ ? upsertCodexToml(t.id, t.path, name)+ : mergeJsonKey(t.id, t.path, t.topKey!, t.entry!, name, name === 'trail' ? ['graft'] : []);+ });}diff --git a/src/hosts/plan.ts b/src/hosts/plan.tsindex 82243934..cddf02bb 100644--- a/src/hosts/plan.ts+++ b/src/hosts/plan.ts@@ -10,13 +10,13 @@import { join } from 'node:path';import { homedir } from 'node:os';import { statSync } from 'node:fs';-import { HOSTS, detectHosts, type DetectProbe, type HostTarget } from './registry.js';+import { HOSTS, detectHosts, hostRelPath, hostWiringName, type DetectProbe, type HostTarget } from './registry.js';import { mcpTargets } from './mcp-config.js';import { hookTargets } from './codex-hooks.js';import { cursorHookTargets } from './cursor-hooks.js';import { antigravitySkillTargets } from './antigravity.js';import { claudeTargets } from '../claude/init.js';-import { brand } from '../brand.js';+import { brand, type Brand } from '../brand.js';import { claudeGlobalTargets } from './claude-global.js';/** Where a write lands. 'global' = outside the repo, affects every project. */@@ -50,14 +50,14 @@ function probeFor(home: string, repo: string): DetectProbe {}/** The instruction-file write for one host, derived from its registry entry. */-function instructionTarget(repo: string, host: HostTarget): PlannedWrite {+function instructionTarget(repo: string, host: HostTarget, name: Brand): PlannedWrite {return {hostId: host.id,id: host.id,- path: join(repo, host.relPath),+ path: join(repo, hostRelPath(host, name)),scope: 'repo',kind: 'instruction',- what: host.kind === 'owned' ? 'graft-owned file' : 'fenced graft section',+ what: host.kind === 'owned' ? `${name}-owned file` : `fenced ${name} section`,};}@@ -70,6 +70,7 @@ export function planInit(repo: string, opts: { home?: string; ids?: string[] } =const home = opts.home ?? homedir();const probe = probeFor(home, repo);const detected = new Set(detectHosts(probe).map((h) => h.id));+ const name = hostWiringName(repo, brand());const plans: HostPlan[] = [// Repo writes plus the user-level copy under `~/.claude` — the picker and@@ -81,11 +82,11 @@ export function planInit(repo: string, opts: { home?: string; ids?: string[] } =name: host.name,detected: detected.has(host.id),writes: [- instructionTarget(repo, host),- ...mcpTargets(repo, [host.id], { home }),+ instructionTarget(repo, host, name),+ ...mcpTargets(repo, [host.id], { home, name }),...(host.id === 'agents' ? hookTargets(home) : []),- ...(host.id === 'cursor' ? cursorHookTargets(repo) : []),- ...(host.id === 'antigravity' ? antigravitySkillTargets(home) : []),+ ...(host.id === 'cursor' ? cursorHookTargets(repo, name) : []),+ ...(host.id === 'antigravity' ? antigravitySkillTargets(home, name) : []),],})),];diff --git a/src/hosts/registry.ts b/src/hosts/registry.tsindex 9bc4e4a7..d3a74e51 100644--- a/src/hosts/registry.ts+++ b/src/hosts/registry.ts@@ -6,9 +6,12 @@* kind: 'section' → upsert the fenced block into a shared file the user owns.* kind: 'owned' → graft owns the whole file; overwrite it each run.*/+import { existsSync, readFileSync } from 'node:fs';import { join } from 'node:path';import { instructionBody, cursorRule, kiroSteering, windsurfRule } from './instructions.js';import { skillTemplate } from '../claude/skill-template.js';+import { markersFor } from './sections.js';+import { repoWiredForTrail, type Brand } from '../brand.js';export interface DetectProbe {home: string;@@ -20,9 +23,10 @@ export interface HostTarget {id: string;name: string;kind: 'section' | 'owned';- /** Target file, relative to the repo root. */+ /** Target file, relative to the repo root, under graft's names (see `hostRelPath`). */relPath: string;- content(): string;+ /** The text, in the spelling of the repo's name for the tool. */+ content(name?: Brand): string;detect(probe: DetectProbe): boolean;}@@ -130,3 +134,52 @@ export function hostIds(): string[] {export function detectHosts(probe: DetectProbe): HostTarget[] {return HOSTS.filter((h) => h.detect(probe));}++/**+ * A host's file under `name`. A file the tool owns carries its name, like+ * Claude Code's skill and shims do (`.cursor/rules/trail.mdc`,+ * `.adal/skills/trail/SKILL.md`); a shared file is the same file either way.+ */+export function hostRelPath(host: HostTarget, name: Brand): string {+ return name === 'trail' && host.kind === 'owned' ? host.relPath.replace(/\bgraft\b/g, 'trail') : host.relPath;+}++/** Cursor's hooks shim is repo-local, so it carries the repo's name too. */+export function cursorHookShimRelPath(name: Brand): string {+ return join('.cursor', 'hooks', `${name}-hooks.cjs`);+}++/**+ * Whether another agent's files in `repo` are already under trail's names: a+ * trail-named file, or a shared file holding trail's block.+ */+export function hostsWiredForTrail(repo: string): boolean {+ if (existsSync(join(repo, cursorHookShimRelPath('trail')))) return true;+ const seen = new Set<string>();+ for (const host of HOSTS) {+ const path = join(repo, hostRelPath(host, 'trail'));+ if (seen.has(path)) continue;+ seen.add(path);+ if (host.kind === 'owned') {+ if (existsSync(path)) return true;+ continue;+ }+ try {+ if (readFileSync(path, 'utf8').includes(markersFor('trail').start)) return true;+ } catch {+ /* not there */+ }+ }+ return false;+}++/**+ * The name the other agents' wiring goes by in `repo`, decided the way Claude+ * Code's is (`wiringName` in claude/init.ts): trail's where `trail init` is+ * wiring it now (`initBrand`) or the repo is already on trail, graft's+ * everywhere else. Read from the repo, not the machine, so a teammate on+ * graft refreshing the files writes the same ones and never flips them back.+ */+export function hostWiringName(repo: string, initBrand?: Brand): Brand {+ return initBrand === 'trail' || repoWiredForTrail(repo) || hostsWiredForTrail(repo) ? 'trail' : 'graft';+}diff --git a/src/hosts/retract.ts b/src/hosts/retract.tsindex e9590a3e..15e94526 100644--- a/src/hosts/retract.ts+++ b/src/hosts/retract.ts@@ -26,15 +26,20 @@import { readFileSync, writeFileSync, existsSync, rmSync, rmdirSync, statSync, readdirSync } from 'node:fs';import { join, dirname } from 'node:path';import { homedir } from 'node:os';-import { HOSTS } from './registry.js';+import { HOSTS, hostRelPath } from './registry.js';import { ALL_MARKERS, type Markers } from './sections.js';import { mcpTargets, stripTomlSection } from './mcp-config.js';import { hookTargets } from './codex-hooks.js';+import { cursorHookTargets } from './cursor-hooks.js';import { antigravitySkillTargets } from './antigravity.js';import { claudeGlobalTargets } from './claude-global.js';import { claudeTargets, claudeTargetsFor } from '../claude/init.js';import { isGraftAllowEntry, isGraftFooterRegex } from '../claude/settings-merge.js';import type { WriteScope } from './plan.js';+import type { Brand } from '../brand.js';++/** Both names a file can go by: graft's, and trail's in a repo that uses trail. */+const NAMES: readonly Brand[] = ['graft', 'trail'];/** What a retraction did to one target. */export type RetractAction =@@ -197,7 +202,7 @@ function removeJsonKey(path: string, topKey: string, apply: boolean): RetractAct}/**- * Delete the `[mcp_servers.graft]` table from a TOML config.+ * Delete the `[mcp_servers.graft]` and `[mcp_servers.trail]` tables from a TOML config.** Line-based on purpose: a real TOML parse-and-reserialize would reformat the* user's whole file. The table runs from its header to the next `[`-header or@@ -205,8 +210,10 @@ function removeJsonKey(path: string, topKey: string, apply: boolean): RetractAct*/function removeTomlSection(path: string, apply: boolean): RetractAction {if (!existsSync(path)) return 'absent';- const { rest: kept, found } = stripTomlSection(readFileSync(path, 'utf8'));- if (!found) return 'absent';+ const graft = stripTomlSection(readFileSync(path, 'utf8'), 'graft');+ const trail = stripTomlSection(graft.rest, 'trail');+ const kept = trail.rest;+ if (!graft.found && !trail.found) return 'absent';if (!apply) return isBlank(kept) ? 'deleted' : 'removed';if (isBlank(kept)) return removeFile(path, true);writeFileSync(path, kept.endsWith('\n') ? kept : `${kept}\n`);@@ -269,8 +276,12 @@ function stripClaudeSettings(path: string, apply: boolean): RetractAction {return 'removed';}-/** Remove graft's PostToolUse/SessionStart/etc. entries from Codex's hooks.json. */-function stripCodexHooks(path: string, apply: boolean): RetractAction {+/**+ * Remove graft's hook entries from a hooks config: Codex's `~/.codex/hooks.json`+ * (PostToolUse/SessionStart/etc.), or Cursor's `.cursor/hooks.json`, whose+ * schema `version` is graft's too, so a file holding nothing else goes.+ */+function stripHookEntries(path: string, apply: boolean, ours: string[] = []): RetractAction {if (!existsSync(path)) return 'absent';let root: Record<string, any>;try {@@ -290,8 +301,9 @@ function stripCodexHooks(path: string, apply: boolean): RetractAction {}if (Object.keys(root.hooks).length === 0) delete root.hooks;if (JSON.stringify(root) === before) return 'absent';- if (!apply) return Object.keys(root).length === 0 ? 'deleted' : 'removed';- if (Object.keys(root).length === 0) return removeFile(path, true);+ const empty = Object.keys(root).every((k) => ours.includes(k));+ if (!apply) return empty ? 'deleted' : 'removed';+ if (empty) return removeFile(path, true);writeFileSync(path, `${JSON.stringify(root, null, 2)}\n`);return 'removed';}@@ -370,17 +382,20 @@ function targets(repo: string, opts: RetractOpts): Target[] {* rewrite it immediately afterwards. Exclude by path as well, so retraction* never depends on what runs next.*/+ // Under both names: init rewrites a kept host under the repo's name and+ // clears the other name's copy itself.const keptPaths = new Set<string>();for (const host of HOSTS) {- if (exclude.has(host.id)) keptPaths.add(join(repo, host.relPath));+ if (exclude.has(host.id)) for (const n of NAMES) keptPaths.add(join(repo, hostRelPath(host, n)));}for (const t of mcpTargets(repo, [...exclude], { home })) keptPaths.add(t.path);if (exclude.has('claude')) {- for (const n of ['graft', 'trail'] as const) for (const t of claudeTargetsFor(repo, n)) keptPaths.add(t.path);+ for (const n of NAMES) for (const t of claudeTargetsFor(repo, n)) keptPaths.add(t.path);for (const t of claudeGlobalTargets(home)) keptPaths.add(t.path);}if (exclude.has('agents')) for (const t of hookTargets(home)) keptPaths.add(t.path);- if (exclude.has('antigravity')) for (const t of antigravitySkillTargets(home)) keptPaths.add(t.path);+ if (exclude.has('cursor')) for (const n of NAMES) for (const t of cursorHookTargets(repo, n)) keptPaths.add(t.path);+ if (exclude.has('antigravity')) for (const n of NAMES) for (const t of antigravitySkillTargets(home, n)) keptPaths.add(t.path);/** Queue a target unless a kept host owns that path, or it's already queued. */const seen = new Set<string>();@@ -390,16 +405,18 @@ function targets(repo: string, opts: RetractOpts): Target[] {out.push(t);};- // 1. Instruction files, one per host. Owned files go wholesale; shared files- // lose only their fenced block.+ // 1. Instruction files, one per host and name. Owned files go wholesale;+ // shared files lose only their fenced block (either name's).for (const host of HOSTS) {if (exclude.has(host.id)) continue;- const path = join(repo, host.relPath);- add(- host.kind === 'owned'- ? { hostId: host.id, path, what: 'graft-owned instruction file', scope: 'repo', run: (a) => removeFile(path, a) }- : { hostId: host.id, path, what: 'fenced graft section', scope: 'repo', run: (a) => stripSection(path, a) },- );+ for (const n of NAMES) {+ const path = join(repo, hostRelPath(host, n));+ add(+ host.kind === 'owned'+ ? { hostId: host.id, path, what: `${n}-owned instruction file`, scope: 'repo', run: (a) => removeFile(path, a) }+ : { hostId: host.id, path, what: 'fenced graft section', scope: 'repo', run: (a) => stripSection(path, a) },+ );+ }}// 1b. Instruction files from hosts that no longer exist in the registry.@@ -442,6 +459,15 @@ function targets(repo: string, opts: RetractOpts): Target[] {] as Target[]) add(t);}+ // 3b. Cursor's repo-local hooks: the shim under either name, and the entries.+ if (!exclude.has('cursor')) {+ for (const n of NAMES) {+ const [shim, config] = cursorHookTargets(repo, n);+ add({ hostId: 'cursor', path: shim.path, what: shim.what, scope: 'repo', run: (a) => removeFile(shim.path, a) });+ add({ hostId: 'cursor', path: config.path, what: config.what, scope: 'repo', run: (a) => stripHookEntries(config.path, a, ['version']) });+ }+ }+// 4. Global: Claude Code's user-level copy, Codex's hook shim + entries, and// Antigravity's shared skill.if (opts.global !== false) {@@ -457,12 +483,12 @@ function targets(repo: string, opts: RetractOpts): Target[] {for (const t of hookTargets(home)) {add({hostId: t.hostId, path: t.path, what: t.what, scope: 'global',- run: (a) => (t.path.endsWith('.json') ? stripCodexHooks(t.path, a) : removeFile(t.path, a)),+ run: (a) => (t.path.endsWith('.json') ? stripHookEntries(t.path, a) : removeFile(t.path, a)),});}}if (!exclude.has('antigravity')) {- for (const t of antigravitySkillTargets(home)) {+ for (const t of NAMES.flatMap((n) => antigravitySkillTargets(home, n))) {add({ hostId: t.hostId, path: t.path, what: t.what, scope: 'global', run: (a) => removeFile(t.path, a) });}}diff --git a/src/hosts/sections.ts b/src/hosts/sections.tsindex 12dd2ed3..458bcd9e 100644--- a/src/hosts/sections.ts+++ b/src/hosts/sections.ts@@ -4,10 +4,15 @@*/import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';import { dirname } from 'node:path';+import type { Brand } from '../brand.js';export const START = '<!-- graft:start -->';export const END = '<!-- graft:end -->';+/** The same block in a repo wired by trail. */+export const TRAIL_START = '<!-- trail:start -->';+export const TRAIL_END = '<!-- trail:end -->';+/*** A brain's rules go in their OWN fenced block, not inside the instruction* block above.@@ -28,10 +33,16 @@ export interface Markers {}export const GRAFT_MARKERS: Markers = { start: START, end: END };+export const TRAIL_MARKERS: Markers = { start: TRAIL_START, end: TRAIL_END };export const BRAIN_MARKERS: Markers = { start: BRAIN_START, end: BRAIN_END };/** Every managed region graft may own in a user-owned file. */-export const ALL_MARKERS: Markers[] = [GRAFT_MARKERS, BRAIN_MARKERS];+export const ALL_MARKERS: Markers[] = [GRAFT_MARKERS, TRAIL_MARKERS, BRAIN_MARKERS];++/** The instruction block's markers under each name. */+export function markersFor(name: Brand): Markers {+ return name === 'trail' ? TRAIL_MARKERS : GRAFT_MARKERS;+}export type UpsertAction = 'created' | 'appended' | 'replaced' | 'unchanged';@@ -58,7 +69,40 @@ function markerLineIndex(lines: string[], marker: string, from = 0): number {return -1;}-export function upsertSection(filePath: string, body: string, markers: Markers = GRAFT_MARKERS): { action: UpsertAction } {+interface Span {+ s: number;+ e: number;+}++/** The start and end line of the block fenced by `markers`, or null. */+function blockSpan(lines: string[], markers: Markers): Span | null {+ const s = markerLineIndex(lines, markers.start);+ const e = s === -1 ? -1 : markerLineIndex(lines, markers.end, s + 1);+ return s !== -1 && e !== -1 ? { s, e } : null;+}++/**+ * `lines` without the block at `sp`, and the blank line that set it off: the+ * one after it, or else the one before it. The file's final newline stays.+ */+function withoutBlock(lines: string[], sp: Span): string[] {+ const blank = (i: number) => i >= 0 && i < lines.length && lines[i].trim() === '';+ let { s, e } = sp;+ if (blank(e + 1) && e + 1 < lines.length - 1) e++;+ else if (blank(s - 1)) s--;+ return [...lines.slice(0, s), ...lines.slice(e + 1)];+}++/**+ * Write `body` into the block fenced by `markers`, keeping the rest of the file.+ *+ * `replaces` names blocks this one supersedes: a repo moving from graft's+ * names to trail's has a `graft:start` block where the `trail:start` one+ * goes. The block takes the place of its own markers if they're there, or of+ * the first superseded block, and any other superseded block goes, so the+ * file never ends up with both.+ */+export function upsertSection(filePath: string, body: string, markers: Markers = GRAFT_MARKERS, replaces: Markers[] = []): { action: UpsertAction } {if (!existsSync(filePath)) {const block = fencedBlock(body, '\n', markers);mkdirSync(dirname(filePath), { recursive: true });@@ -76,6 +120,20 @@ export function upsertSection(filePath: string, body: string, markers: Markers =const lines = text.split(/\r\n|\n/);const s = markerLineIndex(lines, markers.start);const e = s === -1 ? -1 : markerLineIndex(lines, markers.end, s + 1);+ const superseded = replaces.map((m) => blockSpan(lines, m)).filter((sp): sp is Span => sp !== null);+ if (superseded.length > 0) {+ const own = s !== -1 && e !== -1 ? { s, e } : null;+ const at = own ?? superseded[0];+ // Bottom up, so the line numbers of the blocks above stay true.+ let next = lines;+ for (const sp of [...(own ? [own] : []), ...superseded].sort((a, b) => b.s - a.s)) {+ next = sp === at+ ? [...next.slice(0, sp.s), ...fencedBlock(body, '\n', markers).split('\n'), ...next.slice(sp.e + 1)]+ : withoutBlock(next, sp);+ }+ writeFileSync(filePath, next.join(eol));+ return { action: 'replaced' };+ }if (s !== -1 && e !== -1) {const current = lines.slice(s, e + 1).join('\n');if (current === fencedBlock(body, '\n', markers)) return { action: 'unchanged' };diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex 1167ae30..9543428f 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -26,6 +26,7 @@ import {} from '../graph/workspace.js';import type { NodeV1 } from '../graph/types.js';import { canonicalToolName } from './tool-names.js';+import { cmd } from '../brand.js';export interface ToolDef {name: string;@@ -33,10 +34,10 @@ export interface ToolDef {inputSchema: object;}-const NO_GRAPH = 'no graph found — run `graft build` first';+const noGraph = (): string => `no graph found — run \`${cmd('graft build')}\` first`;function unknownSymbolText(query: string): string {- return `no symbol "${query}" in the graph — check spelling or run \`graft build\``;+ return `no symbol "${query}" in the graph — check spelling or run \`${cmd('graft build')}\``;}export const TOOLS: ToolDef[] = [@@ -284,7 +285,7 @@ async function callSingleTool(const symbol = String(args.symbol ?? args.file ?? '');if (!symbol) return { text: 'graft_trace_calls requires a symbol', isError: true };const w = loadGraphCached(contextDirFor(root, dirOverride));- if (!w) return { text: NO_GRAPH, isError: true };+ if (!w) return { text: noGraph(), isError: true };const inOpt = typeof args.in === 'string' && args.in ? { in: args.in } : {};const matches = resolveSymbol(w, symbol, inOpt);if (matches.length === 0) return { text: unknownSymbolText(symbol), isError: true };@@ -307,7 +308,7 @@ async function callSingleTool(const pattern = String(args.pattern ?? '');if (!pattern) return { text: 'graft_find_all requires a pattern', isError: true };const w = loadGraphCached(contextDirFor(root, dirOverride));- if (!w) return { text: NO_GRAPH, isError: true };+ if (!w) return { text: noGraph(), isError: true };const result = grepGraph(w, root, pattern, {ignoreCase: typeof args.ignore_case === 'boolean' ? args.ignore_case : undefined,fixed: typeof args.fixed === 'boolean' ? args.fixed : undefined,@@ -318,7 +319,7 @@ async function callSingleTool(}case 'graft_repo_map': {const w = loadGraphCached(contextDirFor(root, dirOverride));- if (!w) return { text: NO_GRAPH, isError: true };+ if (!w) return { text: noGraph(), isError: true };const maxDirs = typeof args.max_dirs === 'number' && Number.isFinite(args.max_dirs) && args.max_dirs > 0 ? args.max_dirs : undefined;const map = buildRepoMap(w, { maxDirs });return { text: formatRepoMap(map), isError: false };diff --git a/src/search/grep-cli.ts b/src/search/grep-cli.tsindex d2c3fc36..32dd4d0c 100644--- a/src/search/grep-cli.ts+++ b/src/search/grep-cli.ts@@ -12,6 +12,7 @@ import { contextDirFor } from "../context/node-file.js";import { withSavings } from "../context/savings.js";import { loadGraphCached } from "../graph/load.js";import { grepGraph, type GrepGroup, type GrepResult } from "./grep.js";+import { cmd } from "../brand.js";export interface GrepCliOptions {ignoreCase?: boolean;@@ -71,10 +72,10 @@ export function formatGrepResult(result: GrepResult): string {* otherwise a zero-hit result on a stale graph or wrong root reads as "no* matches" when really some files were never searched at all. */export function zeroHitNote(result: GrepResult): string {- const base = `no hits for "${result.pattern}" in ${result.filesSearched} indexed files. The pattern may be too specific — retry graft grep with a bare symbol name or short substring (drop the receiver, full signature, and regex anchors). All indexed code was searched; use raw grep -rn only for genuinely unindexed files (docs, configs, brand-new files)`;+ const base = `no hits for "${result.pattern}" in ${result.filesSearched} indexed files. The pattern may be too specific — retry ${cmd("graft grep")} with a bare symbol name or short substring (drop the receiver, full signature, and regex anchors). All indexed code was searched; use raw grep -rn only for genuinely unindexed files (docs, configs, brand-new files)`;const { files } = result.truncated;if (files === 0) return base;- return `${base} — note: ${files} indexed file${files === 1 ? "" : "s"} could not be read (stale graph? run graft build)`;+ return `${base} — note: ${files} indexed file${files === 1 ? "" : "s"} could not be read (stale graph? run ${cmd("graft build")})`;}/**@@ -89,7 +90,7 @@ export function runGrepCommand(pattern: string, dir: string, opts: GrepCliOptionconst contextDir = contextDirFor(root, opts.globalDir);const graph = loadGraphCached(contextDir);if (!graph) {- console.error("✗ no graph — run graft build first");+ console.error(`✗ no graph — run ${cmd("graft build")} first`);process.exit(1);}diff --git a/src/telemetry/gate.ts b/src/telemetry/gate.tsindex c1190cb9..1aabf294 100644--- a/src/telemetry/gate.ts+++ b/src/telemetry/gate.ts@@ -20,6 +20,7 @@*/import { posthogKey } from './key.js';import { readState } from './identity.js';+import { cmd } from '../brand.js';export type OffReason = 'no-key' | 'do-not-track' | 'ci' | 'disabled';@@ -77,6 +78,6 @@ export function explainOff(reason: OffReason): string {case 'no-key': return 'off — this build has no telemetry key (a fork, or a local `npm run build`); nothing can be sent';case 'do-not-track': return 'off — DO_NOT_TRACK is set in this environment';case 'ci': return 'off — this looks like CI';- case 'disabled': return 'off — you disabled it (`graft telemetry enable` to turn it back on)';+ case 'disabled': return `off — you disabled it (\`${cmd('graft telemetry enable')}\` to turn it back on)`;}}diff --git a/src/telemetry/notice.ts b/src/telemetry/notice.tsindex a9b01b62..93d1c70f 100644--- a/src/telemetry/notice.ts+++ b/src/telemetry/notice.ts@@ -18,8 +18,9 @@ import { explainOff, offReason } from './gate.js';import { peek } from './queue.js';import { buildBatch } from './send.js';import { posthogHost } from './key.js';+import { brand, cmd, inBrand } from '../brand.js';-export const TELEMETRY_DOC_URL = 'https://github.com/NanoNets/context-graph-engine/blob/main/TELEMETRY.md';+export const TELEMETRY_DOC_URL = 'https://github.com/trailhq/Trail-Code/blob/main/TELEMETRY.md';export const NOTICE = ['· graft collects anonymous usage stats (no code, no file paths, no queries).',@@ -36,7 +37,7 @@ export function firstRunNotice(home?: string, env?: NodeJS.ProcessEnv): string |if (offReason(home, env) !== null) return null; // nothing to disclose if nothing can be sentif (readState(home)?.noticeShownAt) return null;patchState({ noticeShownAt: new Date().toISOString() }, home);- return NOTICE;+ return inBrand(NOTICE, brand(env));} catch {return null;}@@ -59,10 +60,10 @@ export function formatStatus(home?: string, env?: NodeJS.ProcessEnv): string {}lines.push(reason === 'disabled'- ? ' enable: graft telemetry enable'- : ' disable: graft telemetry disable (or set DO_NOT_TRACK=1)',+ ? ` enable: ${cmd('graft telemetry enable')}`+ : ` disable: ${cmd('graft telemetry disable')} (or set DO_NOT_TRACK=1)`,);- lines.push(' inspect: graft telemetry debug (prints the exact batch, sends nothing)');+ lines.push(` inspect: ${cmd('graft telemetry debug')} (prints the exact batch, sends nothing)`);return lines.join('\n');}diff --git a/src/upkeep-run.ts b/src/upkeep-run.tsindex 4699c614..82619647 100644--- a/src/upkeep-run.ts+++ b/src/upkeep-run.ts@@ -56,9 +56,11 @@ function rewriteWiring(repo: string, hosts: string[], opts: WiringOpts, toTrail// declined those at init time must keep declining them on every replay.if (hosts.includes('claude'))runInit(repo, { build: false, cliPath: graftCliPath(), statusline: opts.statusline, global: opts.global, ...(toTrail ? { brand: 'trail' as const } : {}) });+ // The other agents move with Claude Code: their graft-named files and+ // fenced blocks are replaced by trail's (see hosts/init.ts).const others = hosts.filter((h) => h !== 'claude');if (others.length)- runHostsInit(repo, { agents: others, global: opts.global, mcp: opts.mcp, hooks: opts.hooks });+ runHostsInit(repo, { agents: others, global: opts.global, mcp: opts.mcp, hooks: opts.hooks, ...(toTrail ? { brand: 'trail' as const } : {}) });if (toTrail && hosts.includes('claude')) readPastSessionsInBackground(repo);}diff --git a/src/upkeep.ts b/src/upkeep.tsindex 206c2ac6..d71be4ae 100644--- a/src/upkeep.ts+++ b/src/upkeep.ts@@ -29,8 +29,8 @@ import { spawn } from 'node:child_process';import { join } from 'node:path';import { homedir } from 'node:os';import { readJson, writeJsonAtomic, cacheDir } from './util/state.js';-import { HOSTS } from './hosts/registry.js';-import { START } from './hosts/sections.js';+import { HOSTS, hostRelPath } from './hosts/registry.js';+import { markersFor } from './hosts/sections.js';import { getNpmViewVersion, readCurrentVersion } from './cli-meta.js';import { brand } from './brand.js';import { graftCliPath } from './claude/paths.js';@@ -232,14 +232,18 @@ export function wiredHostIds(repo: string): string[] {const ids: string[] = [];if (['graft', 'trail'].some((n) => existsSync(join(repo, '.claude', 'helpers', `${n}-hooks.cjs`)))) ids.push('claude');for (const host of HOSTS) {- const path = join(repo, host.relPath);- if (!existsSync(path)) continue;- // A shared file (AGENTS.md, GEMINI.md) counts only if graft's fenced section- // is in it — the user may own the file for entirely unrelated reasons.- if (host.kind === 'section') {- try { if (!readFileSync(path, 'utf8').includes(START)) continue; } catch { continue; }- }- ids.push(host.id);+ // Under either name: a repo on trail has trail's files and blocks.+ const wired = (['graft', 'trail'] as const).some((n) => {+ const path = join(repo, hostRelPath(host, n));+ if (!existsSync(path)) return false;+ // A shared file (AGENTS.md, GEMINI.md) counts only if graft's fenced section+ // is in it — the user may own the file for entirely unrelated reasons.+ if (host.kind === 'section') {+ try { return readFileSync(path, 'utf8').includes(markersFor(n).start); } catch { return false; }+ }+ return true;+ });+ if (wired) ids.push(host.id);}return ids;}diff --git a/src/viz/serve.ts b/src/viz/serve.tsindex 8d7ac1ec..13a6c0ee 100644--- a/src/viz/serve.ts+++ b/src/viz/serve.ts@@ -12,6 +12,7 @@ import { createServer, type Server, type ServerResponse } from "node:http";import { readFileSync, existsSync, watch, type FSWatcher } from "node:fs";import { join } from "node:path";import { assembleContextGraph } from "./assemble.js";+import { cmd } from "../brand.js";export interface VizServerOptions {contextDir: string;@@ -82,18 +83,18 @@ export async function startVizServer(opts: VizServerOptions): Promise<VizServer>if (path === "/api/code-graph") {const file = join(opts.contextDir, ".graph", "wiring.json");if (!existsSync(file)) {- sendJson(res, 404, { error: "no wiring graph in this context dir — run `graft build` first" });+ sendJson(res, 404, { error: `no wiring graph in this context dir — run \`${cmd("graft build")}\` first` });return;}try {const parsed = JSON.parse(readFileSync(file, "utf8"));if (parsed?.meta?.version !== 1) {- sendJson(res, 404, { error: "wiring.json has an unsupported version — regenerate with `graft build`" });+ sendJson(res, 404, { error: `wiring.json has an unsupported version — regenerate with \`${cmd("graft build")}\`` });return;}sendJson(res, 200, parsed);} catch {- sendJson(res, 404, { error: "wiring.json is unreadable — regenerate with `graft build`" });+ sendJson(res, 404, { error: `wiring.json is unreadable — regenerate with \`${cmd("graft build")}\`` });}return;}diff --git a/test/app-sources-context.test.ts b/test/app-sources-context.test.tsindex 14b64d51..bc04759b 100644--- a/test/app-sources-context.test.ts+++ b/test/app-sources-context.test.ts@@ -33,7 +33,7 @@ function fixture(): string {put(root, '.claude/skills/deploy/SKILL.md', '---\nname: deploy\n---\nAlways deploy from main.\n');put(root, '.claude/skills/graft/SKILL.md', '---\nname: graft\n---\ngraft teaches graft\n');put(root, '.claude/skills/empty/README.md', 'no skill file here\n');- put(root, 'web/AGENTS.md', 'before\n<!-- graft:start -->\ngraft block\n<!-- graft:end -->\nafter\n');+ put(root, 'web/AGENTS.md', 'before\n<!-- graft:start -->\ngraft block\n<!-- graft:end -->\nafter\n<!-- trail:start -->\ntrail block\n<!-- trail:end -->\n');return root;}@@ -75,6 +75,7 @@ test('readAgentInstructions carries them all as agent_instructions, graft blocksassert.ok(got.every((s) => s.kind === 'agent_instructions'));const web = got.find((s) => s.path === 'web/AGENTS.md')!;assert.doesNotMatch(web.text, /graft block/);+ assert.doesNotMatch(web.text, /trail block/, 'the block trail init writes is stripped too');assert.match(web.text, /before[\s\S]*after/);assert.ok(!paths.includes('.claude/skills/graft/SKILL.md'));});diff --git a/test/claude-hook-layers.test.ts b/test/claude-hook-layers.test.tsnew file mode 100644index 00000000..28c5ed89--- /dev/null+++ b/test/claude-hook-layers.test.ts@@ -0,0 +1,59 @@+/**+ * `init` registers the hooks in the repo and in ~/.claude, and Claude Code runs+ * both. One copy answers each event, or every prompt gets its learnings twice.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { globalCopyCovers } from "../src/claude/hook-layers.js";+import { hooksShim } from "../src/claude/shim-template.js";++/** A home with ~/.claude hooks for `events`, calling a shim with `shim` as its bytes. */+function homeWith(events: string[], shim = hooksShim()): { home: string; globalShim: string } {+ const home = mkdtempSync(join(tmpdir(), "hook-layers-"));+ const helpers = join(home, ".claude", "helpers");+ mkdirSync(helpers, { recursive: true });+ const globalShim = join(helpers, "graft-hooks.cjs");+ writeFileSync(globalShim, shim);+ const hooks = Object.fromEntries(+ events.map((e) => [e, [{ hooks: [{ type: "command", command: `node "${globalShim.replace(/\\/g, "/")}" ${e}` }] }]]),+ );+ writeFileSync(join(home, ".claude", "settings.json"), JSON.stringify({ hooks }));+ return { home, globalShim };+}++const repoShim = join(tmpdir(), "some-repo", ".claude", "helpers", "trail-hooks.cjs");++test("the repo's copy stands down for an event the ~/.claude copy answers", () => {+ const { home } = homeWith(["session-start", "prompt"]);+ assert.equal(globalCopyCovers("session-start", repoShim, home), true);+ assert.equal(globalCopyCovers("prompt", repoShim, home), true);+ assert.equal(globalCopyCovers("stop", repoShim, home), false, "an event only the repo registers still runs there");+});++test("the ~/.claude copy itself always runs", () => {+ const { home, globalShim } = homeWith(["session-start"]);+ assert.equal(globalCopyCovers("session-start", globalShim, home), false);+});++test("a ~/.claude shim an older graft wrote doesn't count: it can't find trail", () => {+ const { home } = homeWith(["session-start"], "const pkg = require.resolve('@nanonets/graft/package.json');");+ assert.equal(globalCopyCovers("session-start", repoShim, home), false);+});++test("Cursor's and Codex's shims never stand down for Claude's hooks", () => {+ const { home } = homeWith(["session-start"]);+ assert.equal(globalCopyCovers("session-start", join(tmpdir(), "some-repo", ".cursor", "hooks", "graft-hooks.cjs"), home), false);+ assert.equal(globalCopyCovers("session-start", join(home, ".codex", "graft-hooks.cjs"), home), false);+});++test("no ~/.claude settings, or none of ours: the repo's copy runs", () => {+ const home = mkdtempSync(join(tmpdir(), "hook-layers-empty-"));+ assert.equal(globalCopyCovers("session-start", repoShim, home), false);+ mkdirSync(join(home, ".claude"), { recursive: true });+ writeFileSync(join(home, ".claude", "settings.json"), JSON.stringify({ hooks: { SessionStart: [{ hooks: [{ command: "echo hi" }] }] } }));+ assert.equal(globalCopyCovers("session-start", repoShim, home), false);+ assert.equal(globalCopyCovers("session-start", undefined, home), false);+});diff --git a/test/claude-shim-template.test.ts b/test/claude-shim-template.test.tsindex 66f12fc3..50bbc4b9 100644--- a/test/claude-shim-template.test.ts+++ b/test/claude-shim-template.test.ts@@ -27,8 +27,8 @@ for (const [name, src] of [['statusline', statuslineShim()], ['hooks', hooksShimassert.match(src, /st\.uid !== process\.getuid\(\)/);assert.match(src, /st\.mode & 0o022/);// 2. repo node_modules via require.resolve from the project dir- // under both names: a teammate with only @trailhq/trail installed still gets hooks- assert.match(src, /const PKGS = \['@trailhq\/trail', '@nanonets\/graft'\];/);+ // under both names: a teammate with only @trailhq/trail-code installed still gets hooks+ assert.match(src, /const PKGS = \['@trailhq\/trail-code', '@nanonets\/graft', '@trailhq\/trail'\];/);assert.match(src, /require\.resolve\(name \+ '\/package\.json', \{ paths: \[base\] \}\)/);assert.match(src, /fromPkg\(dir\)/);// 3. legacy execPath/../lib guess retaineddiff --git a/test/hosts-trail.test.ts b/test/hosts-trail.test.tsnew file mode 100644index 00000000..af2b5e45--- /dev/null+++ b/test/hosts-trail.test.ts@@ -0,0 +1,270 @@+/**+ * The other agents' files under trail's names.+ *+ * A machine with only `@trailhq/trail-code` has no `graft` command, so a repo+ * wired by trail tells every agent to run `trail …`, names the files the tool+ * owns after trail (as Claude Code's skill and shims are), and registers the+ * MCP server as `trail`. A repo moving from graft's names to trail's ends up+ * with trail's files only, and uninstall removes either.+ */+import { test } from 'node:test';+import assert from 'node:assert/strict';++// Pin the MCP launch command to the npx form, whatever this machine has installed.+process.env.GRAFT_MCP_NPX = '1';+process.env.TRAIL_NO_FETCH = '1';+delete process.env.GRAFT_NO_TRAIL_SWITCH;++import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { delimiter, join, relative } from 'node:path';+import { spawnSync } from 'node:child_process';+import { runHostsInit } from '../src/hosts/init.js';+import { HOSTS, hostRelPath, hostWiringName } from '../src/hosts/registry.js';+import { instructionBody, cursorRule } from '../src/hosts/instructions.js';+import { trailSpelling } from '../src/claude/skill-template.js';+import { GRAFT_MARKERS, TRAIL_MARKERS, fencedBlock, upsertSection } from '../src/hosts/sections.js';+import { registerMcpConfigs } from '../src/hosts/mcp-config.js';+import { changed, runRetract } from '../src/hosts/retract.js';+import { runInit } from '../src/claude/init.js';+import { runUpkeep } from '../src/upkeep-run.js';+import { readStamp, runningVersion, wiredHostIds } from '../src/upkeep.js';+import { BRAND_ENV } from '../src/brand.js';+import { tmpRepo } from './helpers.js';++const ALL = HOSTS.map((h) => h.id);+/** A graft command an agent would be told to run. `graft/` (the code map's folder) is not one. */+const GRAFT_COMMAND = /\bgraft (ask|grep|callers|skeleton|map|build|check|stats|note|mcp)\b/;++/** Every file under `dir`, repo-relative, skipping the graph and git. */+function filesUnder(dir: string): string[] {+ const out: string[] = [];+ const walk = (d: string) => {+ for (const e of readdirSync(d, { withFileTypes: true })) {+ if (e.name === '.git' || e.name === 'graft') continue;+ const p = join(d, e.name);+ if (e.isDirectory()) walk(p);+ else out.push(relative(dir, p));+ }+ };+ walk(dir);+ return out.sort();+}++/** A scratch home where every agent with a machine-wide config is installed. */+function agentHome(): string {+ const home = tmpRepo('trail-hosts-home');+ for (const d of [['.codex'], ['.config', 'opencode'], ['.gemini', 'config']]) mkdirSync(join(home, ...d), { recursive: true });+ return home;+}++test('trail spelling: renamed commands, the name in prose, the code map folder kept', () => {+ assert.equal(trailSpelling('run `graft check` in CI'), 'run `trail build --check` in CI');+ assert.equal(trailSpelling('`graft stats --json`'), '`trail status --json`');+ assert.equal(trailSpelling('`graft checkout x` and `graft ask "q"`'), '`trail checkout x` and `trail ask "q"`');+ assert.equal(trailSpelling('## Graft — see graft/INDEX.md, graft-hooks.cjs, graft_find_code'), '## Trail — see graft/INDEX.md, graft-hooks.cjs, graft_find_code');+});++test('the instruction text under trail names trail commands only; under graft it is what it was', () => {+ const trail = instructionBody('trail');+ assert.match(trail, /^## Trail — repo context graph/);+ assert.match(trail, /`trail ask "<your question>" --source`/);+ assert.match(trail, /`trail grep "<literal>"`/);+ assert.match(trail, /`trail callers <symbol>`/);+ assert.match(trail, /`graft\/INDEX\.md`/, 'the code map still lives in graft/');+ assert.doesNotMatch(trail, GRAFT_COMMAND);+ assert.match(cursorRule('trail'), /^---\ndescription: Use the Trail context graph in graft\/ before exploring source\nalwaysApply: true\n---\n## Trail/);+ assert.equal(instructionBody('graft'), instructionBody());+ assert.match(instructionBody(), /^## Graft — repo context graph/);+});++test('trail init for every agent: trail-named files, trail commands, a trail server', () => {+ const home = agentHome();+ const repo = tmpRepo('trail-hosts');+ const r = runHostsInit(repo, { all: true, home, brand: 'trail' });+ assert.equal(r.written.length, ALL.length);++ const files = filesUnder(repo);+ assert.deepEqual(files.filter((f) => /\bgraft\b/.test(f)), [], `no graft-named file in the repo: ${files.join(', ')}`);+ for (const rel of [+ join('.cursor', 'rules', 'trail.mdc'),+ join('.cursor', 'hooks', 'trail-hooks.cjs'),+ join('.kiro', 'steering', 'trail.md'),+ join('.windsurf', 'rules', 'trail.md'),+ join('.adal', 'skills', 'trail', 'SKILL.md'),+ join('.grok', 'skills', 'trail', 'SKILL.md'),+ ]) assert.ok(files.includes(rel), `${rel} written`);++ // Every instruction file tells the agent to run trail, never graft.+ for (const host of HOSTS) {+ const text = readFileSync(join(repo, hostRelPath(host, 'trail')), 'utf8');+ assert.doesNotMatch(text, GRAFT_COMMAND, `${host.id} names a graft command`);+ assert.match(text, /\btrail (ask|grep)\b/, `${host.id} names trail's`);+ }+ const agents = readFileSync(join(repo, 'AGENTS.md'), 'utf8');+ assert.equal(agents.split(TRAIL_MARKERS.start).length - 1, 1, 'one block, shared by three hosts');+ assert.ok(!agents.includes(GRAFT_MARKERS.start));+ assert.match(readFileSync(join(repo, '.adal', 'skills', 'trail', 'SKILL.md'), 'utf8'), /^---\nname: trail\n/);++ // The MCP server is trail's, under trail's name, in every config.+ const npx = { command: 'npx', args: ['-y', '@trailhq/trail-code', 'mcp'] };+ for (const rel of [join('.cursor', 'mcp.json'), join('.gemini', 'settings.json'), join('.kiro', 'settings', 'mcp.json')]) {+ assert.deepEqual(JSON.parse(readFileSync(join(repo, rel), 'utf8')).mcpServers, { trail: npx }, rel);+ }+ assert.deepEqual(JSON.parse(readFileSync(join(repo, 'opencode.json'), 'utf8')).mcp, { trail: { type: 'local', command: ['npx', '-y', '@trailhq/trail-code', 'mcp'], enabled: true } });+ assert.deepEqual(JSON.parse(readFileSync(join(home, '.gemini', 'config', 'mcp_config.json'), 'utf8')).mcpServers, { trail: npx });+ for (const toml of [join(repo, '.grok', 'config.toml'), join(home, '.codex', 'config.toml')]) {+ assert.equal(readFileSync(toml, 'utf8'), '[mcp_servers.trail]\ncommand = "npx"\nargs = ["-y", "@trailhq/trail-code", "mcp"]\n', toml);+ }+ assert.ok(existsSync(join(home, '.gemini', 'skills', 'trail', 'SKILL.md')));+ assert.ok(!existsSync(join(home, '.gemini', 'skills', 'graft')));+ const hooks = JSON.parse(readFileSync(join(repo, '.cursor', 'hooks.json'), 'utf8'));+ assert.match(hooks.hooks.postToolUse[0].command, /trail-hooks\.cjs" cursor-post-tool$/);++ // A teammate on graft refreshing the same repo writes the same files: it never flips back.+ assert.equal(hostWiringName(repo), 'trail');+ const again = runHostsInit(repo, { all: true, home });+ assert.ok(again.written.every((w) => w.action === 'unchanged'), JSON.stringify(again.written));+ assert.ok(again.mcp.every((w) => w.action === 'unchanged'), JSON.stringify(again.mcp));+});++test('a graft-wired repo moved to trail keeps one copy of everything, under trail', () => {+ const home = agentHome();+ const repo = tmpRepo('graft-to-trail-hosts');+ writeFileSync(join(repo, 'AGENTS.md'), '# House rules\n\nBe kind.\n');+ runHostsInit(repo, { all: true, home });+ assert.ok(readFileSync(join(repo, 'AGENTS.md'), 'utf8').includes(GRAFT_MARKERS.start), 'wired as graft');+ assert.equal(hostWiringName(repo), 'graft');++ runHostsInit(repo, { all: true, home, brand: 'trail' });+ const files = filesUnder(repo);+ assert.deepEqual(files.filter((f) => /\bgraft\b/.test(f)), [], `graft's copies are gone: ${files.join(', ')}`);+ assert.ok(!existsSync(join(repo, '.adal', 'skills', 'graft')), 'and their folders');+ const agents = readFileSync(join(repo, 'AGENTS.md'), 'utf8');+ assert.equal(agents, `# House rules\n\nBe kind.\n\n${fencedBlock(instructionBody('trail'), '\n', TRAIL_MARKERS)}\n`, 'the graft block became the trail one, in place');+ for (const rel of ['GEMINI.md', join('.github', 'copilot-instructions.md')]) {+ const text = readFileSync(join(repo, rel), 'utf8');+ assert.ok(!text.includes(GRAFT_MARKERS.start) && text.split(TRAIL_MARKERS.start).length === 2, rel);+ }+ for (const rel of [join('.cursor', 'mcp.json'), join('.gemini', 'settings.json'), join('.kiro', 'settings', 'mcp.json')]) {+ assert.deepEqual(Object.keys(JSON.parse(readFileSync(join(repo, rel), 'utf8')).mcpServers), ['trail'], rel);+ }+ assert.deepEqual(Object.keys(JSON.parse(readFileSync(join(repo, 'opencode.json'), 'utf8')).mcp), ['trail']);+ assert.deepEqual(Object.keys(JSON.parse(readFileSync(join(home, '.gemini', 'config', 'mcp_config.json'), 'utf8')).mcpServers), ['trail']);+ for (const toml of [join(repo, '.grok', 'config.toml'), join(home, '.codex', 'config.toml')]) {+ const text = readFileSync(toml, 'utf8');+ assert.ok(!text.includes('[mcp_servers.graft]') && text.includes('[mcp_servers.trail]'), toml);+ }+ assert.ok(!existsSync(join(home, '.gemini', 'skills', 'graft')));+ const hooks = JSON.parse(readFileSync(join(repo, '.cursor', 'hooks.json'), 'utf8'));+ for (const [event, entries] of Object.entries<unknown[]>(hooks.hooks)) {+ assert.equal(entries.length, 1, `${event}: one entry`);+ assert.match(JSON.stringify(entries), /trail-hooks\.cjs/);+ }+});++test('a file holding both blocks keeps one: trail\'s, where trail\'s was', () => {+ const dir = tmpRepo('both-blocks');+ const graft = fencedBlock('old graft text', '\n', GRAFT_MARKERS);+ const trail = fencedBlock('old trail text', '\n', TRAIL_MARKERS);+ const want = fencedBlock('new text', '\n', TRAIL_MARKERS);+ const cases: Array<[string, string]> = [+ [`# Notes\n\n${trail}\n\n${graft}\n`, `# Notes\n\n${want}\n`],+ [`${graft}\n\n${trail}\n`, `${want}\n`],+ [`# Notes\n\n${graft}\n\nMore notes.\n`, `# Notes\n\n${want}\n\nMore notes.\n`],+ [`# Notes\r\n\r\n${graft.replace(/\n/g, '\r\n')}\r\n`, `# Notes\r\n\r\n${want.replace(/\n/g, '\r\n')}\r\n`],+ ];+ for (const [i, [before, after]] of cases.entries()) {+ const f = join(dir, `AGENTS-${i}.md`);+ writeFileSync(f, before);+ assert.equal(upsertSection(f, 'new text', TRAIL_MARKERS, [GRAFT_MARKERS]).action, 'replaced');+ assert.equal(readFileSync(f, 'utf8'), after, `case ${i}`);+ assert.equal(upsertSection(f, 'new text', TRAIL_MARKERS, [GRAFT_MARKERS]).action, 'unchanged', `case ${i} converged`);+ }+});++test('a graft repo leaves a machine-wide trail server alone instead of adding graft\'s beside it', () => {+ const home = agentHome();+ const codex = join(home, '.codex', 'config.toml');+ const trailTable = '[mcp_servers.trail]\ncommand = "trail"\nargs = ["mcp"]\n';+ writeFileSync(codex, trailTable);+ const ag = join(home, '.gemini', 'config', 'mcp_config.json');+ writeFileSync(ag, `${JSON.stringify({ mcpServers: { trail: { command: 'trail', args: ['mcp'] } } }, null, 2)}\n`);+ const repo = tmpRepo('graft-repo-trail-machine');+ const ws = registerMcpConfigs(repo, ['agents', 'antigravity', 'cursor'], { home });+ assert.deepEqual(ws.map((w) => [w.id, w.action]), [['codex', 'unchanged'], ['opencode', 'created'], ['antigravity', 'unchanged'], ['cursor', 'created']]);+ assert.equal(readFileSync(codex, 'utf8'), trailTable);+ assert.deepEqual(Object.keys(JSON.parse(readFileSync(ag, 'utf8')).mcpServers), ['trail']);+ assert.deepEqual(Object.keys(JSON.parse(readFileSync(join(repo, '.cursor', 'mcp.json'), 'utf8')).mcpServers), ['graft'], 'the repo\'s own config is still graft\'s');+});++test('uninstall removes the wiring under either name, keeping the user\'s words', () => {+ const home = agentHome();+ const repo = tmpRepo('uninstall-both');+ writeFileSync(join(repo, 'AGENTS.md'), '# House rules\n');+ runHostsInit(repo, { all: true, home, brand: 'trail' });+ // A teammate on an older graft added its copies back beside trail's.+ writeFileSync(join(repo, 'AGENTS.md'), `${readFileSync(join(repo, 'AGENTS.md'), 'utf8')}\n${fencedBlock('graft', '\n', GRAFT_MARKERS)}\n`);+ mkdirSync(join(repo, '.cursor', 'rules'), { recursive: true });+ writeFileSync(join(repo, '.cursor', 'rules', 'graft.mdc'), 'old\n');+ writeFileSync(join(repo, '.grok', 'config.toml'), `${readFileSync(join(repo, '.grok', 'config.toml'), 'utf8')}\n[mcp_servers.graft]\ncommand = "graft"\n`);+ mkdirSync(join(home, '.gemini', 'skills', 'graft'), { recursive: true });+ writeFileSync(join(home, '.gemini', 'skills', 'graft', 'SKILL.md'), 'old\n');++ assert.ok(changed(runRetract(repo, { home, apply: true })).length > 0);+ assert.deepEqual(filesUnder(repo), ['AGENTS.md']);+ assert.equal(readFileSync(join(repo, 'AGENTS.md'), 'utf8'), '# House rules\n');+ assert.ok(!existsSync(join(home, '.gemini', 'skills', 'trail')) && !existsSync(join(home, '.gemini', 'skills', 'graft')));+ assert.ok(!existsSync(join(home, '.codex', 'config.toml')));+ assert.deepEqual(changed(runRetract(repo, { home, apply: true })), [], 'a second sweep finds nothing');+});++test('a session start that moves a graft repo to trail moves the other agents too', () => {+ const repo = tmpRepo('move-hosts');+ spawnSync('git', ['init', '-q'], { cwd: repo });+ const home = mkdtempSync(join(tmpdir(), 'move-hosts-home-'));+ const saved = { PATH: process.env.PATH, HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE, TRAIL_HOME: process.env.TRAIL_HOME, [BRAND_ENV]: process.env[BRAND_ENV] };+ Object.assign(process.env, { HOME: home, USERPROFILE: home, TRAIL_HOME: join(home, '.trail') });+ try {+ delete process.env[BRAND_ENV];+ runInit(repo, { build: false, global: false });+ runHostsInit(repo, { agents: ['agents', 'cursor', 'gemini', 'kiro'], home, global: false });+ runUpkeep(repo, runningVersion(), { background: false, home });+ const hosts = readStamp(repo)?.hosts;+ assert.deepEqual(hosts, ['agents', 'antigravity', 'claude', 'cursor', 'gemini', 'hermes', 'kiro'], 'AGENTS.md reads as all three of its hosts');++ const bin = mkdtempSync(join(tmpdir(), 'bin-trail-'));+ writeFileSync(join(bin, 'trail'), '#!/bin/sh\nexit 0\n');+ chmodSync(join(bin, 'trail'), 0o755);+ process.env.PATH = `${bin}${delimiter}${saved.PATH}`;+ assert.match(runUpkeep(repo, runningVersion(), { background: false, home }).lines.join('\n'), /just moved to it/);++ const files = filesUnder(repo);+ assert.deepEqual(files.filter((f) => /\bgraft\b/.test(f)), [], `nothing graft-named left: ${files.join(', ')}`);+ for (const rel of ['AGENTS.md', 'GEMINI.md', join('.cursor', 'rules', 'trail.mdc'), join('.kiro', 'steering', 'trail.md')]) {+ const text = readFileSync(join(repo, rel), 'utf8');+ assert.doesNotMatch(text, GRAFT_COMMAND, rel);+ assert.ok(!text.includes(GRAFT_MARKERS.start), `${rel}: no graft block left`);+ }+ assert.deepEqual(Object.keys(JSON.parse(readFileSync(join(repo, '.cursor', 'mcp.json'), 'utf8')).mcpServers), ['trail']);+ assert.deepEqual(wiredHostIds(repo).sort(), hosts, 'the same agents, found under trail\'s names');+ assert.doesNotMatch(runUpkeep(repo, runningVersion(), { background: false, home }).lines.join('\n'), /just moved/, 'once');+ } finally {+ for (const [k, v] of Object.entries(saved)) if (v === undefined) delete process.env[k]; else process.env[k] = v;+ }+});++test('CLI: trail init --dry-run names trail\'s files', () => {+ const repo = tmpRepo('trail-dry');+ const home = tmpRepo('trail-dry-home');+ const r = spawnSync(process.execPath, ['--import', 'tsx', join('src', 'bin', 'trail.ts'), 'init', repo, '--no-build', '--agents', 'cursor', 'kiro', 'adal', '--dry-run'], {+ encoding: 'utf8',+ env: { ...process.env, HOME: home, USERPROFILE: home, DO_NOT_TRACK: '1', TRAIL_INVOKED_AS: undefined, TRAIL_HOME: undefined },+ });+ assert.equal(r.status, 0, r.stderr);+ for (const rel of [join('.cursor', 'rules', 'trail.mdc'), join('.kiro', 'steering', 'trail.md'), join('.adal', 'skills', 'trail', 'SKILL.md')]) {+ assert.ok(r.stderr.includes(rel), `${rel} in ${r.stderr}`);+ }+ assert.doesNotMatch(r.stderr, /graft\.mdc|steering[\\/]graft\.md|skills[\\/]graft/);+ assert.deepEqual(readdirSync(repo), [], 'a dry run writes nothing');+});diff --git a/test/trail-cloud.test.ts b/test/trail-cloud.test.tsindex 70de93e5..cd2a0e7a 100644--- a/test/trail-cloud.test.ts+++ b/test/trail-cloud.test.ts@@ -10,14 +10,14 @@import { test } from "node:test";import assert from "node:assert/strict";import { spawnSync } from "node:child_process";-import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { BRAND_ENV } from "../src/brand.js";import { formatOverlap, overlapsWith, refreshBranches } from "../src/notes/branches.js";import { listNotes, writeNote } from "../src/notes/notes.js";import { flushActivity, learningsPayload, recordActivity, syncRepo } from "../src/cloud/workspace-sync.js";-import type { Cloud } from "../src/cloud/workspace.js";+import { clearCloud, writeCloud, type Cloud } from "../src/cloud/workspace.js";process.env.DO_NOT_TRACK = "1";process.env[BRAND_ENV] = "trail";@@ -161,29 +161,67 @@ test("a repo outside the workspace is never uploaded", async () => {assert.equal(sent.length, 0);});-test("uses are kept until the machine is connected, then sent once", async () => {- const at = new Date().toISOString();- recordActivity({ repo: "github.com/acme/retry", kind: "search", asker: "Kumar", session: "s1", query: "retry count", files: ["client.go"], shown_paths: ["a.md"], shown_authors: ["Anirudh"], at });- recordActivity({ repo: "github.com/acme/retry", kind: "check", asker: "Kumar", session: "s1", query: "", files: ["client.go"], shown_paths: ["a.md"], shown_authors: ["Anirudh"], at });- const outbox = join(process.env.TRAIL_HOME!, "outbox.jsonl");- assert.equal(readFileSync(outbox, "utf8").trim().split("\n").length, 2);+/** One use of the learnings in `repo`, at `at`. */+function use(repo: string, kind: "search" | "check", at = new Date().toISOString()) {+ return { repo, kind, asker: "Kumar", session: "s1", query: kind === "search" ? "retry count" : "", files: ["client.go"], shown_paths: ["a.md"], shown_authors: ["Anirudh"], at };+}++const outbox = () => join(process.env.TRAIL_HOME!, "outbox.jsonl");++test("not connected, a use is never written down: no outbox, cloud features on or off", () => {+ clearCloud();+ for (const cloud of [undefined, "1"]) {+ if (cloud) process.env.TRAIL_CLOUD = cloud;+ else delete process.env.TRAIL_CLOUD;+ recordActivity(use("github.com/acme/retry", "search"));+ recordActivity(use("github.com/acme/retry", "check"));+ }+ delete process.env.TRAIL_CLOUD;+ assert.equal(existsSync(outbox()), false);+});++test("connected, only the workspace's repos are written down, and sent once", async () => {const { cloud, sent, fetchImpl } = cloudFor(["github.com/acme/retry"]);- assert.equal(await flushActivity(cloud, fetchImpl), 2);- assert.equal(sent[0]!.path, "/api/cli/activity");- assert.deepEqual(sent[0]!.body.events.map((e: any) => e.kind), ["search", "check"]);- assert.equal(existsSync(outbox), false, "sent, so gone");- assert.equal(await flushActivity(cloud, fetchImpl), 0, "nothing twice");+ cloud.linkedAt = Date.now() - 1000;+ writeCloud(cloud);+ try {+ recordActivity(use("github.com/acme/retry", "search"));+ recordActivity(use("github.com/acme/other", "search"));+ recordActivity(use("github.com/acme/retry", "check"));+ assert.equal(readFileSync(outbox(), "utf8").trim().split("\n").length, 2, "the other repo's search stays on this machine");+ assert.equal(await flushActivity(cloud, fetchImpl), 2);+ assert.equal(sent[0]!.path, "/api/cli/activity");+ assert.deepEqual(sent[0]!.body.events.map((e: any) => [e.repo, e.kind]), [["github.com/acme/retry", "search"], ["github.com/acme/retry", "check"]]);+ assert.equal(existsSync(outbox()), false, "sent, so gone");+ assert.equal(await flushActivity(cloud, fetchImpl), 0, "nothing twice");+ } finally {+ clearCloud();+ }+});++test("what an older trail queued before connecting, or for another repo, is dropped at send, not sent", async () => {+ const { cloud, sent, fetchImpl } = cloudFor(["github.com/acme/retry"]);+ cloud.linkedAt = Date.parse("2026-10-10T12:00:00Z");+ const lines = [+ use("github.com/acme/retry", "search", "2026-10-10T11:59:59Z"),+ use("github.com/acme/secret", "search", "2026-10-10T12:30:00Z"),+ use("github.com/acme/retry", "check", "2026-10-10T12:30:00Z"),+ ];+ writeFileSync(outbox(), lines.map((l) => JSON.stringify(l)).join("\n") + "\n");+ assert.equal(await flushActivity(cloud, fetchImpl), 1);+ assert.deepEqual(sent[0]!.body.events.map((e: any) => [e.repo, e.kind, e.at]), [["github.com/acme/retry", "check", "2026-10-10T12:30:00Z"]]);+ assert.equal(existsSync(outbox()), false, "the rest is gone too");});test("a failed send keeps the uses for next time", async () => {- recordActivity({ repo: "github.com/acme/retry", kind: "search", asker: "Kumar", session: "s2", query: "q", files: [], shown_paths: ["a.md"], shown_authors: ["Anirudh"], at: new Date().toISOString() });- const { cloud } = cloudFor([]);+ const { cloud } = cloudFor(["github.com/acme/retry"]);+ recordActivity(use("github.com/acme/retry", "search"), cloud);const down = (async () => {throw new Error("offline");}) as typeof fetch;assert.equal(await flushActivity(cloud, down), 0);- const outbox = join(process.env.TRAIL_HOME!, "outbox.jsonl");- assert.equal(readFileSync(outbox, "utf8").trim().split("\n").length, 1);+ assert.equal(readFileSync(outbox(), "utf8").trim().split("\n").length, 1);+ rmSync(outbox(), { force: true });mkdirSync(process.env.TRAIL_HOME!, { recursive: true });});diff --git a/test/trail-name.test.ts b/test/trail-name.test.tsindex 2901b0c4..a21a611e 100644--- a/test/trail-name.test.ts+++ b/test/trail-name.test.ts@@ -12,7 +12,7 @@ import { spawnSync } from "node:child_process";import { chmodSync, existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { brand, cmd, graftNotice, noticeStampPath, tag } from "../src/brand.js";+import { brand, cmd, graftNotice, handoverStampPath, noticeStampPath, strandedRepoNotice, tag, trailHandoverLine } from "../src/brand.js";import { track } from "../src/telemetry/track.js";import { commandInvokesGraft } from "../src/claude/session-metrics.js";import { savingsLine, sumSavingsFooters } from "../src/context/savings.js";@@ -82,6 +82,49 @@ test("agents, pipes, CI and trail itself never see the notice, and it isn't stamassert.equal(existsSync(noticeStampPath(home)), false, "nothing stamped");});+// --- a repo whose graft-era hooks can't reach trail ---++/** A repo wired by graft 0.21: a hook shim that looks for @nanonets/graft alone. */+function graftEraRepo(shim = "require.resolve('@nanonets/graft/package.json')"): string {+ const repo = mkdtempSync(join(tmpdir(), "graft-era-"));+ mkdirSync(join(repo, ".git"));+ mkdirSync(join(repo, ".claude", "helpers"), { recursive: true });+ writeFileSync(join(repo, ".claude", "helpers", "graft-hooks.cjs"), shim);+ return repo;+}++const TRAIL = { TRAIL_INVOKED_AS: "trail", PATH: "" };+const STRANDED =+ "· this repo's agent hooks were set up by an older graft and can't find trail. run trail init here once to move the repo over";++test("trail in a graft-era repo, with no graft to answer its hooks, says how to move the repo", () => {+ const repo = graftEraRepo();+ assert.equal(strandedRepoNotice({ cwd: repo, tty: true, env: TRAIL }), STRANDED);+ mkdirSync(join(repo, "src", "deep"), { recursive: true });+ assert.equal(strandedRepoNotice({ cwd: join(repo, "src", "deep"), tty: true, env: TRAIL }), STRANDED, "from a subfolder too");+});++test("no stranded line once something can answer the hooks, or the repo already moved", () => {+ const bin = mkdtempSync(join(tmpdir(), "graft-bin-"));+ const exe = join(bin, process.platform === "win32" ? "graft.cmd" : "graft");+ writeFileSync(exe, "");+ chmodSync(exe, 0o755);+ assert.equal(strandedRepoNotice({ cwd: graftEraRepo(), tty: true, env: { ...TRAIL, PATH: bin } }), null, "graft installed");+ assert.equal(strandedRepoNotice({ cwd: graftEraRepo("const PKGS = ['@trailhq/trail-code', '@nanonets/graft'];"), tty: true, env: TRAIL }), null, "a shim that looks for trail");+ const moved = graftEraRepo();+ writeFileSync(join(moved, ".claude", "helpers", "trail-hooks.cjs"), "");+ assert.equal(strandedRepoNotice({ cwd: moved, tty: true, env: TRAIL }), null, "already on trail");+ assert.equal(strandedRepoNotice({ cwd: tmpRepo(), tty: true, env: TRAIL }), null, "never wired");+});++test("agents, pipes, CI and graft itself never see the stranded line", () => {+ const repo = graftEraRepo();+ assert.equal(strandedRepoNotice({ cwd: repo, tty: false, env: TRAIL }), null, "no terminal");+ assert.equal(strandedRepoNotice({ cwd: repo, tty: true, env: { ...TRAIL, CLAUDECODE: "1" } }), null, "Claude Code");+ assert.equal(strandedRepoNotice({ cwd: repo, tty: true, env: { ...TRAIL, CI: "true" } }), null, "CI");+ assert.equal(strandedRepoNotice({ cwd: repo, tty: true, env: { PATH: "" } }), null, "graft");+});+// --- what parses the output ---test("the savings footer is read under either name", () => {@@ -90,7 +133,7 @@ test("the savings footer is read under either name", () => {test("a shell command running trail counts as a retrieval, like graft", () => {assert.equal(commandInvokesGraft('trail ask "auth" --source'), true);- assert.equal(commandInvokesGraft("npx -y @trailhq/trail grep foo"), true);+ assert.equal(commandInvokesGraft("npx -y @trailhq/trail-code grep foo"), true);assert.equal(commandInvokesGraft("cd x && trail callers run"), true);assert.equal(commandInvokesGraft("node dist/bin/trail.js ask x"), true);assert.equal(commandInvokesGraft("graft ask x"), true);@@ -267,3 +310,28 @@ test("both tool vocabularies count as retrievals", async () => {assert.equal(isGraftMcpTool("mcp__trail__trail_trace_calls"), true);assert.equal(isGraftMcpTool("mcp__graft__graft_find_all"), true);});++// --- the agent's line on a machine with graft and no trail ---++test("on graft without trail, the agent is told once a week how to get trail", () => {+ const home = scratchHome();+ const now = Date.parse("2026-10-14T10:00:00Z");+ const line = trailHandoverLine({ env: { PATH: "" }, home, now });+ assert.match(line ?? "", /graft is now Trail-code/);+ assert.match(line ?? "", /`graft upgrade` adds it and graft keeps working/);+ assert.equal(trailHandoverLine({ env: { PATH: "" }, home, now: now + 3 * 86400_000 }), null, "not again that week");+ assert.ok(trailHandoverLine({ env: { PATH: "" }, home, now: now + 8 * 86400_000 }), "again the next week");+});++test("no handover line once trail is installed, under trail, in CI, or opted out", () => {+ const bin = mkdtempSync(join(tmpdir(), "graft-bin-"));+ const exe = join(bin, process.platform === "win32" ? "trail.cmd" : "trail");+ writeFileSync(exe, "");+ chmodSync(exe, 0o755);+ const home = scratchHome();+ assert.equal(trailHandoverLine({ env: { PATH: bin }, home }), null, "trail on PATH");+ assert.equal(trailHandoverLine({ env: { PATH: "", TRAIL_INVOKED_AS: "trail" }, home }), null, "trail");+ assert.equal(trailHandoverLine({ env: { PATH: "", CI: "true" }, home }), null, "CI");+ assert.equal(trailHandoverLine({ env: { PATH: "", GRAFT_NO_RENAME_NOTICE: "1" }, home }), null, "opted out");+ assert.equal(existsSync(handoverStampPath(home)), false, "nothing stamped");+});diff --git a/test/trail-notes.test.ts b/test/trail-notes.test.tsindex 530d3aad..11902b93 100644--- a/test/trail-notes.test.ts+++ b/test/trail-notes.test.ts@@ -294,6 +294,8 @@ test("trail note saves a learning in .trail/learnings/ to commit, ask shows it tassert.match(ask.out, /\.trail\/learnings\/\d{4}-\d{2}-\d{2}-bbox/);assert.match(ask.out, /\[(trail|graft)\] learnings saved ≈ [\d,]+ tokens/, "what reusing it saved, for the tally");}+ // Not connected to a workspace: what was searched stays unrecorded, so a later sign-in has nothing old to send.+ assert.equal(existsSync(join(home, ".trail", "outbox.jsonl")), false, "no outbox before connecting");const st = run("trail", ["status", d], home);assert.equal(st.status, 0, st.err);@@ -392,6 +394,19 @@ test("hooks speak trail only in a repo wired for it, on a machine with trail insassert.equal(adoptRepoBrand(plain, { PATH: bin, TRAIL_INVOKED_AS: "trail" }), "trail", "a name already set is kept");});+test("Cursor's and Codex's hooks speak trail in a repo whose only trail wiring is theirs", async () => {+ const { adoptRepoBrand } = await import("../src/brand.js");+ const { hostsWiredForTrail } = await import("../src/hosts/registry.js");+ const bin = mkdtempSync(join(tmpdir(), "notes-bin-"));+ writeFileSync(join(bin, process.platform === "win32" ? "trail.cmd" : "trail"), "");+ const cursorOnly = tmpRepo("brand-cursor");+ mkdirSync(join(cursorOnly, ".cursor", "rules"), { recursive: true });+ writeFileSync(join(cursorOnly, ".cursor", "rules", "trail.mdc"), "");+ assert.equal(adoptRepoBrand(cursorOnly, { PATH: bin }, hostsWiredForTrail), "trail");+ assert.equal(adoptRepoBrand(cursorOnly, { PATH: bin }), "graft", "without the hosts check, only .claude counts");+ assert.equal(adoptRepoBrand(tmpRepo("brand-none"), { PATH: bin }, hostsWiredForTrail), "graft");+});+// --- wiring under trail's names ---test("trail init moves a graft-wired repo to trail's names, and uninstall takes either set out", () => {@@ -414,7 +429,7 @@ test("trail init moves a graft-wired repo to trail's names, and uninstall takesassert.match(settings, /trail-statusline\.cjs/);const mcp = JSON.parse(readFileSync(join(d, ".mcp.json"), "utf8"));assert.deepEqual(Object.keys(mcp.mcpServers), ["trail"]);- assert.deepEqual(mcp.mcpServers.trail, { command: "npx", args: ["-y", "@trailhq/trail", "mcp"] });+ assert.deepEqual(mcp.mcpServers.trail, { command: "npx", args: ["-y", "@trailhq/trail-code", "mcp"] });// Running it again changes nothing.const again = run("trail", ["init", d, "--agents", "claude", "--yes", "--no-global"], home);diff --git a/test/trail-nudge.test.ts b/test/trail-nudge.test.tsindex 009fb98e..cc845b78 100644--- a/test/trail-nudge.test.ts+++ b/test/trail-nudge.test.ts@@ -10,7 +10,7 @@import { test } from "node:test";import assert from "node:assert/strict";import { spawnSync } from "node:child_process";-import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { BRAND_ENV } from "../src/brand.js";@@ -161,6 +161,23 @@ test("the background wait registers the link with the picker's repos, then conneassert.deepEqual(lines(dir, "ask", "s3"), [], "only once");});+test("connecting sends nothing queued before it, whatever its timestamp", async () => {+ freshHome();+ const { dir, key } = repo();+ lines(dir, "ask", "s1");+ // What an older trail left: a search from before anyone signed in, in this repo and another.+ const at = new Date(Date.now() + 60_000).toISOString();+ const old = (repo: string) => JSON.stringify({ repo, kind: "search", asker: "Priya", session: "s0", query: "rate limit", files: ["a.go"], shown_paths: ["x.md"], shown_authors: ["Priya"], at });+ const outbox = join(process.env.TRAIL_HOME!, "outbox.jsonl");+ writeFileSync(outbox, `${old(key)}\n${old("github.com/acme/private")}\n`);+ const trail = fakeTrail();+ const got = await waitForConnect({ fetchImpl: trail.fetchImpl, sleep: async () => {} });+ assert.ok(got && "cloud" in got);+ assert.equal(trail.sent.filter((s) => s.path === "/api/cli/activity").length, 0, "no activity sent");+ assert.equal(existsSync(outbox), false, "and none kept to send later");+ rmSync(join(process.env.TRAIL_HOME!, "cloud.json"));+});+test("a spent link stops the wait and is forgotten, so the next session mints a new one", async () => {freshHome();const { dir } = repo();diff --git a/test/trail-spelling.test.ts b/test/trail-spelling.test.tsnew file mode 100644index 00000000..b12e83f2--- /dev/null+++ b/test/trail-spelling.test.ts@@ -0,0 +1,53 @@+/**+ * Under trail, what the agent reads names commands it can run. A trail-only+ * install has no `graft` binary, so a hint that says `graft ask` costs a failed+ * tool call. Under graft the same text is unchanged.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { BRAND_ENV } from "../src/brand.js";+import { weakMatchNudge } from "../src/claude/format.js";+import { hasSavingsTally } from "../src/claude/tally.js";+import type { SessionState } from "../src/claude/state.js";+import { savingsTurnNudge } from "../src/context/savings.js";+import { zeroHitNote } from "../src/search/grep-cli.js";+import type { GrepResult } from "../src/search/grep.js";++/** A graft command a trail-only machine can't run. */+const GRAFT_COMMAND = /\bgraft (ask|build|grep|callers|skeleton|map|blast|telemetry)\b|\[graft\]|graft saved/;++function under<T>(name: "trail" | "graft", fn: () => T): T {+ const saved = process.env[BRAND_ENV];+ process.env[BRAND_ENV] = name;+ try {+ return fn();+ } finally {+ if (saved === undefined) delete process.env[BRAND_ENV];+ else process.env[BRAND_ENV] = saved;+ }+}++const grepMiss = { pattern: "x", filesSearched: 3, truncated: { files: 1 } } as unknown as GrepResult;++test("hints the agent reads name trail's commands under trail", () => {+ const lines = under("trail", () => [+ weakMatchNudge({ nudges: 0 } as SessionState, 0.1)!,+ savingsTurnNudge(1200),+ zeroHitNote(grepMiss),+ ]);+ for (const line of lines) {+ assert.doesNotMatch(line, GRAFT_COMMAND, line);+ assert.match(line, /trail/, line);+ }+});++test("under graft the same hints keep graft's words", () => {+ assert.match(under("graft", () => weakMatchNudge({ nudges: 0 } as SessionState, 0.1)!), /^\[graft\] .*`graft ask "<your task>" --source`/);+ assert.match(under("graft", () => savingsTurnNudge(1200)), /🌱 graft saved/);+});++test("a trail tally counts as telling the user what was saved", () => {+ assert.equal(hasSavingsTally("🌱 trail saved ~12k tokens (~$0.04) this turn, 3 calls"), true);+ assert.equal(hasSavingsTally("🌱 graft saved ~12k tokens this turn"), true);+ assert.equal(hasSavingsTally("trail is a good name"), false);+});diff --git a/test/upkeep-hooks.test.ts b/test/upkeep-hooks.test.tsindex 86d56805..7390086c 100644--- a/test/upkeep-hooks.test.ts+++ b/test/upkeep-hooks.test.ts@@ -6,7 +6,7 @@import { test } from 'node:test';import assert from 'node:assert/strict';import { mkdirSync, writeFileSync, existsSync } from 'node:fs';-import { join } from 'node:path';+import { delimiter, dirname, join } from 'node:path';import { main } from '../src/claude/hooks.js';import { readStamp, runningVersion, updateCachePath } from '../src/upkeep.js';import { tmpRepo } from './helpers.js';@@ -119,3 +119,22 @@ test('a nudge still lands in a wired repo with no graph built yet', async () =>const ctx = contextOf(await runHook('session-start', repo, homeWithCache('hook-nograph-home', '99.0.0')));assert.match(ctx, /99\.0\.0 available/, 'the no-INDEX.md path still reports upkeep');});++test('a repo graft set up, on a machine without trail, hands the agent the trail line once a week', async () => {+ const path = process.env.PATH;+ const ci = process.env.CI;+ // node and git, and no trail command; and not CI, where the line stays quiet+ process.env.PATH = [dirname(process.execPath), '/usr/bin', '/bin'].join(delimiter);+ delete process.env.CI;+ try {+ const home = homeWithCache('hook-handover-home', null);+ const first = contextOf(await runHook('session-start', wiredRepo('hook-handover'), home));+ assert.match(first, /graft is now Trail-code/);+ assert.match(first, /`graft upgrade` adds it/);+ const again = contextOf(await runHook('session-start', wiredRepo('hook-handover-2'), home));+ assert.doesNotMatch(again, /graft is now Trail-code/, 'once a week, not every session');+ } finally {+ process.env.PATH = path;+ if (ci !== undefined) process.env.CI = ci;+ }+});