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
feat(claude-md): add graft claude-md pull to write accepted CLAUDE.md changes (#467)
anirudhkumar-nanonets5eb5886e9a15
diff --git a/src/brain/claude-md.ts b/src/brain/claude-md.tsnew file mode 100644index 00000000..0aeb132a--- /dev/null+++ b/src/brain/claude-md.ts@@ -0,0 +1,211 @@+/**+ * `graft claude-md pull`: write the CLAUDE.md changes accepted in Trail into+ * this checkout's instruction file.+ *+ * Trail compares the repository's CLAUDE.md with what its history says and+ * suggests edits and new sections; a person accepts some of them on the brain's+ * CLAUDE.md page. This fetches the accepted ones, applies them to the local+ * file, and tells Trail which it wrote so the page stops listing them.+ *+ * The file is edited line by line, never regenerated, so everything a change+ * does not touch comes back byte for byte. An edit whose text is no longer in+ * its section means the local file has moved on since Trail read it; that+ * change is reported and left, never guessed at. Same rules as Trail's own+ * ComposeClaudeMd, which is what the page's preview shows.+ */+import { baseUrlFor, type BrainLink } from "./link.js";++/** One accepted change, as Trail sends it. */+export interface ClaudeMdChange {+ id: string;+ kind: "edit" | "add";+ /** edit: the section it rewrites. add: the new section's heading. */+ heading: string;+ /** add: the section it goes after; "" = end of file. */+ after_heading?: string;+ /** edit: the text to replace; "" = append to the section. */+ find?: string;+ text: string;+ reason?: string;+}++export interface ClaudeMdPull {+ /** The file Trail read, e.g. "CLAUDE.md"; "" when the repo had none. */+ path: string;+ head_sha: string;+ changes: ClaudeMdChange[];+}++export interface ApplyResult {+ text: string;+ /** Written by this pull. */+ written: ClaudeMdChange[];+ /** Already in the file (committed by someone else): nothing to write. */+ present: ClaudeMdChange[];+ /** Could not be placed; the file was left as it is for these. */+ skipped: Array<{ change: ClaudeMdChange; why: string }>;+}++/** GET /api/public/brains/:id/claude-md — the accepted changes. */+export async function fetchAcceptedChanges(+ link: BrainLink,+ fetchImpl: typeof fetch = fetch,+): Promise<ClaudeMdPull | { error: string }> {+ const url = `${baseUrlFor(link)}/api/public/brains/${encodeURIComponent(link.brainId)}/claude-md`;+ try {+ const res = await fetchImpl(url, {+ headers: { authorization: `Bearer ${link.token}`, accept: "application/json" },+ signal: AbortSignal.timeout(15_000),+ });+ const body = await res.text();+ if (res.status === 404 || res.status === 503) {+ return { error: "this brain has no CLAUDE.md suggestions yet — its Trail may be older than the feature" };+ }+ if (!res.ok) return { error: `Trail refused the pull: ${res.status} ${body.slice(0, 200)}` };+ const parsed = JSON.parse(body) as Partial<ClaudeMdPull>;+ return { path: parsed.path ?? "", head_sha: parsed.head_sha ?? "", changes: parsed.changes ?? [] };+ } catch (e) {+ return { error: `could not reach Trail: ${e instanceof Error ? e.message : e}` };+ }+}++/** POST /api/public/brains/:id/claude-md/applied — what this pull wrote. */+export async function markApplied(link: BrainLink, ids: string[], fetchImpl: typeof fetch = fetch): Promise<boolean> {+ if (ids.length === 0) return true;+ const url = `${baseUrlFor(link)}/api/public/brains/${encodeURIComponent(link.brainId)}/claude-md/applied`;+ try {+ // Trail takes at most 100 per request.+ for (let i = 0; i < ids.length; i += 100) {+ const res = await fetchImpl(url, {+ method: "POST",+ headers: {+ authorization: `Bearer ${link.token}`,+ "content-type": "application/json",+ accept: "application/json",+ },+ body: JSON.stringify({ ids: ids.slice(i, i + 100) }),+ signal: AbortSignal.timeout(15_000),+ });+ if (!res.ok) return false;+ }+ return true;+ } catch {+ return false;+ }+}++interface Section {+ title: string;+ level: number;+ /** Line index of the heading. */+ head: number;+ /** One past the last line: the next heading at the same or a higher level. */+ end: number;+}++const HEADING = /^(#{1,6})\s+(.+?)\s*#*\s*$/;++/** Every ATX heading outside code fences, with the lines it owns. */+function sectionsOf(lines: string[]): Section[] {+ const heads: Array<{ line: number; level: number; title: string }> = [];+ let fence = false;+ lines.forEach((ln, i) => {+ const t = ln.trim();+ if (t.startsWith("```") || t.startsWith("~~~")) {+ fence = !fence;+ return;+ }+ if (fence) return;+ const m = HEADING.exec(ln);+ if (m) heads.push({ line: i, level: m[1]!.length, title: m[2]!.trim() });+ });+ return heads.map((h, i) => {+ let end = lines.length;+ for (let j = i + 1; j < heads.length; j++) {+ if (heads[j]!.level <= h.level) {+ end = heads[j]!.line;+ break;+ }+ }+ return { title: h.title, level: h.level, head: h.line, end };+ });+}++const norm = (s: string) => s.trim().toLowerCase();++/** Trim the blank lines a section ends with, so appended text sits under its content. */+function lastContentLine(lines: string[], s: Section): number {+ let i = s.end;+ while (i > s.head + 1 && lines[i - 1]!.trim() === "") i--;+ return i;+}++/**+ * Apply accepted changes to the file's text. Pure: reads nothing, writes+ * nothing, so the command and the tests share it.+ */+export function applyChanges(original: string, changes: ClaudeMdChange[]): ApplyResult {+ const crlf = original.includes("\r\n");+ let lines = original.replace(/\r\n/g, "\n").split("\n");+ const out: ApplyResult = { text: original, written: [], present: [], skipped: [] };++ // Edits first, against headings that exist; then additions, which may go+ // after a section an edit just touched.+ const ordered = [...changes.filter((c) => c.kind === "edit"), ...changes.filter((c) => c.kind === "add")];+ for (const c of ordered) {+ const sections = sectionsOf(lines);+ if (c.kind === "edit") {+ const s = sections.find((x) => norm(x.title) === norm(c.heading));+ if (!s) {+ out.skipped.push({ change: c, why: `no “${c.heading}” section in the file` });+ continue;+ }+ const body = lines.slice(s.head + 1, s.end).join("\n");+ const text = c.text.replace(/\r\n/g, "\n");+ const find = (c.find ?? "").replace(/\r\n/g, "\n");+ if (text.trim() && body.includes(text.trim())) {+ out.present.push(c);+ continue;+ }+ if (!find) {+ const at = lastContentLine(lines, s);+ lines = [...lines.slice(0, at), ...text.trimEnd().split("\n"), ...lines.slice(at)];+ out.written.push(c);+ continue;+ }+ const idx = body.indexOf(find);+ if (idx < 0) {+ out.skipped.push({ change: c, why: `the text it rewrites is no longer in “${c.heading}”` });+ continue;+ }+ const next = body.slice(0, idx) + text + body.slice(idx + find.length);+ lines = [...lines.slice(0, s.head + 1), ...next.split("\n"), ...lines.slice(s.end)];+ out.written.push(c);+ continue;+ }++ // add+ if (sections.some((x) => norm(x.title) === norm(c.heading))) {+ out.present.push(c);+ continue;+ }+ const block = [`## ${c.heading.trim()}`, "", ...c.text.replace(/\r\n/g, "\n").trim().split("\n")];+ const after = c.after_heading ? sections.find((x) => norm(x.title) === norm(c.after_heading!)) : undefined;+ if (after) {+ const at = lastContentLine(lines, after);+ // A blank line either side, whatever the file had there.+ const tail = lines.slice(at);+ lines = [...lines.slice(0, at), "", ...block, ...(tail.length > 0 && tail[0]!.trim() !== "" ? [""] : []), ...tail];+ } else {+ while (lines.length > 0 && lines[lines.length - 1]!.trim() === "") lines.pop();+ lines = lines.length > 0 ? [...lines, "", ...block] : block;+ lines.push("");+ }+ out.written.push(c);+ }++ let text = lines.join("\n");+ if (out.written.length > 0 && !text.endsWith("\n")) text += "\n";+ out.text = out.written.length > 0 ? (crlf ? text.replace(/\n/g, "\r\n") : text) : original;+ return out;+}diff --git a/src/cli.ts b/src/cli.tsindex c1037526..a28f9dce 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -31,6 +31,7 @@ import {} from "./brain/push.js";import type { HistoryThread } from "./app/history.js";import { readLink, writeLink } from "./brain/link.js";+import { applyChanges, fetchAcceptedChanges, markApplied } from "./brain/claude-md.js";import { watchBuild } from "./brain/watch.js";import { openBrowser, signupUrl, startHandoff } from "./brain/signup.js";import { contextDirFor } from "./context/node-file.js";@@ -1481,6 +1482,66 @@ brainconsole.error("· still building after 15 minutes — it has not failed, it is just long. Watch it finish in your browser.");});+const claudeMd = program+ .command("claude-md")+ .description("The CLAUDE.md changes this repo's brain suggested and you accepted in Trail");++claudeMd+ .command("pull")+ .description("Write the CLAUDE.md changes you accepted in Trail into this repo's instruction file")+ .argument("[dir]", "target repo directory", ".")+ .option("--dry-run", "show what would change without writing the file or telling Trail")+ .action(async (dir: string, opts: { dryRun?: boolean }) => {+ const repo = resolve(dir);+ const link = readLink(repo);+ if (!link) {+ console.error("✗ this repo has no brain attached — run `graft brain push` first");+ process.exitCode = 1;+ return;+ }+ const pulled = await fetchAcceptedChanges(link);+ if ("error" in pulled) {+ console.error(`✗ ${pulled.error}`);+ process.exitCode = 1;+ return;+ }+ if (pulled.changes.length === 0) {+ console.error("· nothing accepted yet — accept suggestions on the brain's CLAUDE.md page, then pull again");+ return;+ }+ // The file Trail read, or a new CLAUDE.md when the repo had none.+ const rel = pulled.path || "CLAUDE.md";+ const file = join(repo, rel);+ const { existsSync, readFileSync, writeFileSync } = await import("node:fs");+ const before = existsSync(file) ? readFileSync(file, "utf8") : "";+ const result = applyChanges(before, pulled.changes);++ for (const c of result.written) console.error(` + ${c.kind === "add" ? "new section" : "edit"} · ${c.heading}`);+ for (const c of result.present) console.error(` = already in the file · ${c.heading}`);+ for (const s of result.skipped) console.error(` ! skipped · ${s.change.heading} — ${s.why}`);++ if (opts.dryRun) {+ console.error(`· dry run: ${result.written.length} change(s) would be written to ${rel}; nothing was written`);+ return;+ }+ if (result.written.length > 0) writeFileSync(file, result.text);+ // Written now or already there: either way the page should stop listing it.+ const done = [...result.written, ...result.present].map((c) => c.id);+ const told = await markApplied(link, done);+ if (result.written.length > 0) {+ console.error(`✓ wrote ${result.written.length} change(s) to ${rel} — review and commit it like any other edit`);+ } else if (result.present.length > 0) {+ console.error(`✓ ${rel} already has every accepted change`);+ }+ if (!told) console.error("⚠ could not tell Trail which changes were written; the page may still list them");+ if (result.skipped.length > 0) {+ console.error(+ `· ${result.skipped.length} change(s) no longer match the local file — edit them on the CLAUDE.md page, or apply them by hand`,+ );+ process.exitCode = 1;+ }+ });+brain.command("status").description("Show the attached brain, how many rules are cached, and how many still match the code")diff --git a/test/claude-md-pull.test.ts b/test/claude-md-pull.test.tsnew file mode 100644index 00000000..9ee79cf1--- /dev/null+++ b/test/claude-md-pull.test.ts@@ -0,0 +1,134 @@+/**+ * `graft claude-md pull` edits a file people also edit by hand, so what matters+ * is that it touches only what a change names, never guesses when the file has+ * moved on, and never writes the same change twice.+ */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { applyChanges, fetchAcceptedChanges, markApplied, type ClaudeMdChange } from '../src/brain/claude-md.js';+import type { BrainLink } from '../src/brain/link.js';++const FILE = [+ '# chalk',+ '',+ 'Terminal string styling.',+ '',+ '## Commands',+ '',+ '- `npm test` runs the test suite with ava.',+ '- `npx xo` lints the code.',+ '',+ '```bash',+ '## not a heading',+ '```',+ '',+ '## Architecture',+ '',+ '- `source/index.js` builds the chainable instance.',+ '',+].join('\n');++const edit = (over: Partial<ClaudeMdChange> = {}): ClaudeMdChange => ({+ id: 'e1',+ kind: 'edit',+ heading: 'Commands',+ find: '- `npm test` runs the test suite with ava.',+ text: '- `npm test` runs xo, c8 and ava. Always run the whole script, never ava alone.',+ ...over,+});+const add = (over: Partial<ClaudeMdChange> = {}): ClaudeMdChange => ({+ id: 'a1',+ kind: 'add',+ heading: 'Breaking changes',+ after_heading: 'Commands',+ text: 'Every exported name is public API. Deprecate for one major first.',+ ...over,+});++test('an edit replaces only its own text, and the rest comes back byte for byte', () => {+ const r = applyChanges(FILE, [edit()]);+ assert.deepEqual(r.written.map((c) => c.id), ['e1']);+ assert.equal(r.text, FILE.replace('- `npm test` runs the test suite with ava.', edit().text));+});++test('a new section goes after the one it names, with a blank line either side', () => {+ const r = applyChanges(FILE, [add()]);+ assert.match(r.text, /- `npx xo` lints the code\.\n\n```bash\n## not a heading\n```\n\n## Breaking changes\n\nEvery exported name is public API\. Deprecate for one major first\.\n\n## Architecture/);+});++test('a new section with no anchor goes at the end', () => {+ const r = applyChanges(FILE, [add({ after_heading: '' })]);+ assert.ok(r.text.endsWith('## Breaking changes\n\nEvery exported name is public API. Deprecate for one major first.\n'));+});++test('an edit whose text is gone is skipped, not guessed at', () => {+ const moved = FILE.replace('runs the test suite with ava', 'runs everything');+ const r = applyChanges(moved, [edit()]);+ assert.equal(r.written.length, 0);+ assert.equal(r.skipped.length, 1);+ assert.equal(r.text, moved, 'the file is untouched');+});++test('a heading inside a code fence is not a section', () => {+ const r = applyChanges(FILE, [edit({ heading: 'not a heading' })]);+ assert.equal(r.skipped.length, 1);+});++test('changes already in the file are reported as present, not written again', () => {+ const once = applyChanges(FILE, [edit(), add()]).text;+ const twice = applyChanges(once, [edit(), add()]);+ assert.equal(twice.written.length, 0);+ assert.deepEqual(twice.present.map((c) => c.id).sort(), ['a1', 'e1']);+ assert.equal(twice.text, once);+});++test('an empty find appends to the end of the section', () => {+ const r = applyChanges(FILE, [edit({ find: '', text: '- `npm run bench` runs the benchmarks.' })]);+ assert.match(r.text, /```\n- `npm run bench` runs the benchmarks\.\n\n## Architecture/);+});++test('a repo with no CLAUDE.md gets one from the accepted additions', () => {+ const r = applyChanges('', [add({ after_heading: '' })]);+ assert.equal(r.text, '## Breaking changes\n\nEvery exported name is public API. Deprecate for one major first.\n');+});++test('CRLF files stay CRLF', () => {+ const crlf = FILE.replace(/\n/g, '\r\n');+ const r = applyChanges(crlf, [edit()]);+ assert.ok(!/[^\r]\n/.test(r.text), 'no bare LF introduced');+ assert.ok(r.text.includes('never ava alone.'));+});++// --- the two calls ------------------------------------------------------------++const link = { brainId: 'b1', token: 'gbt_1.x', baseUrl: 'http://trail.test' } as unknown as BrainLink;+const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });++test('pull reads the accepted changes with the brain token', async () => {+ let seen: { url: string; auth: string } | null = null;+ const got = await fetchAcceptedChanges(link, (async (u: string, init?: RequestInit) => {+ seen = { url: u, auth: String((init?.headers as Record<string, string>).authorization) };+ return json({ path: 'CLAUDE.md', head_sha: 'abc', changes: [edit()] });+ }) as typeof fetch);+ assert.ok(!('error' in got) && got.changes.length === 1);+ assert.equal(seen!.url, 'http://trail.test/api/public/brains/b1/claude-md');+ assert.equal(seen!.auth, 'Bearer gbt_1.x');++ const older = await fetchAcceptedChanges(link, (async () => json({ error: 'nope' }, 404)) as typeof fetch);+ assert.ok('error' in older);+});++test('applied ids are reported in batches of at most 100', async () => {+ const bodies: string[][] = [];+ const ok = await markApplied(+ link,+ Array.from({ length: 150 }, (_, i) => `id${i}`),+ (async (_u: string, init?: RequestInit) => {+ bodies.push((JSON.parse(String(init?.body)) as { ids: string[] }).ids);+ return json({ applied: 1 });+ }) as typeof fetch,+ );+ assert.equal(ok, true);+ assert.deepEqual(bodies.map((b) => b.length), [100, 50]);+});