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
Merge origin/main into feat/cloud-pair-rebased
Shrish Dwivedi478d7f66cd5a
diff --cc src/cli.tsindex 35f43b4f,0d672dc8..05743edc--- a/src/cli.ts+++ b/src/cli.ts@@@ -58,29 -57,16 +58,32 @@@ import { normalizePathPrefix } from "./import { latestSession, formatSessionStats, sessionInputRate } from "./claude/session-metrics.js";import { listSessionIds, readSession, sessionDir } from "./claude/state.js";import { costLabel, listNotes, noteName, notePlace, noteTargets, readingTokens, savedByNote, commitLines, PERSONAL_SAVED_LINE, PR_SPEEDUP, SECTIONS, tokensWorthSaying, sectionLead, shortDate, tokensLabel, writeNote, type Note, mentionedFiles } from "./notes/notes.js";+ import { findLearning, liveLearnings } from "./notes/learning-fields.js";import { aboutTerms, currentSessionCost } from "./notes/session-cost.js";import { beginPastRead, finishPastRead, type Finding } from "./notes/cold-start.js";+import { skippedSkillLines, type SavedSkill } from "./skills/found-skill.js";- import { beginReviewRead, finishReviewRead, type ReviewFinding } from "./notes/pr-reviews.js";+ import { anchoredReviews, beginReviewRead, finishReviewRead, type ReviewFinding } from "./notes/pr-reviews.js";+ import { finishMemoryRead, memoryCandidates, offeredBefore, type MemoryCandidate } from "./notes/memory-notes.js";+import { finishPair, PairRun, validPairCode } from "./cloud/pair.js";import { currentBranch, noteAuthor, teammatesOn } from "./notes/git-facts.js";+ import { gateNote, namesRepoSymbol, symbolCandidates, trackedFiles } from "./notes/note-gate.js";import { confirm, fold, getSkill, learn, listSkills, publish, skillForAgent, skillName, skillStatus, type LearnResult } from "./skills/skills.js";+import { recordLookup } from "./cloud/lookup-activity.js";import { clearPending, cloudLines, loginLink, sessionKey, waitForConnect } from "./cloud/nudge.js";-import { addRepo, clearCloud, cloudEnabled, fetchMe, fetchTeam, isError, readCloud, writeCloud, type Cloud } from "./cloud/workspace.js";+import { addRepo, clearCloud, cloudEnabled, fetchMe, fetchTeam, isError, readCloud, trailUrl, writeCloud, type Cloud } from "./cloud/workspace.js";+import {+ claimConnectCode,+ connectAgain,+ offlineLine,+ learningsSummary,+ machineName,+ normalizeCode,+ OnboardingReporter,+ repoRef,+ teammatesChecked,+ teammatesFromGit,+ tokensOnOneLookup,+} from "./cloud/onboarding.js";import { inWorkspace, maybeSyncInBackground, recordActivity, runSyncChild, syncRepo } from "./cloud/workspace-sync.js";import type { CheckResult } from "./check/types.js";import { checkLocally } from "./check/local-check.js";@@@ -1719,23 -1666,28 +1790,29 @@@ async function runInitCommand(dir: stri}}- // Under trail: what init learned from past sessions and PR reviews, where- // this repo's learnings are, and how many there already are.+ // Under trail: what init learned, where this repo's learnings are, and how+ // many there already are. The team's come from what is tied to the code:+ // what reviewers kept flagging on merged PRs, and Claude Code's notes about+ // the repo on this machine. What the person kept telling Claude is theirs.let learnedNow = false;+ let skillsWritten: SavedSkill[] = [];- if (TRAIL && (pastRead || reviewRead)) {+ let teamSaved = 0;+ const memory: MemoryCandidate[] = TRAIL && wantClaude ? memoryCandidates(repo, { offered: offeredBefore(repo) }) : [];+ if (TRAIL && (pastRead || reviewRead || memory.length)) {if (pastRead && !pastRead.done) console.error("· still reading your past sessions…");const fromSessions = pastRead ? (await pastRead.result).findings : [];if (reviewRead && !reviewRead.done) console.error("· still reading PR reviews…");- const fromReviews = reviewRead ? (await reviewRead.result).findings : [];- // On a terminal, the person ticks which to keep in one list for both- // sources, all ticked to start; a scripted run, or one with --yes, keeps- // them all. Cancelling saves none, and the next init asks again.+ const fromReviews = reviewRead ? anchoredReviews(repo, (await reviewRead.result).findings) : [];+ // On a terminal, the person ticks which to keep in one list, the team's+ // first and ticked, their own unticked. A scripted run, or one with+ // --yes, keeps the team's and what they told Claude. Cancelling saves+ // none, and the next init asks again.const picked =- process.stdin.isTTY && process.stderr.isTTY && !opts.yes && !pair && fromSessions.length + fromReviews.length- process.stdin.isTTY && process.stderr.isTTY && !opts.yes && fromReviews.length + memory.length + fromSessions.length++ process.stdin.isTTY && process.stderr.isTTY && !opts.yes && !pair && fromReviews.length + memory.length + fromSessions.length? await pickLearnings([- ...fromSessions.map((f) => ({ title: f.title, forTeam: f.for === "team", sessions: f.sessions.length })),- ...fromReviews.map((f) => ({ title: f.title, forTeam: true, prs: f.prs.length })),+ ...fromReviews.map((f) => ({ title: f.title, forTeam: true, prs: f.prs })),+ ...memory.map((c) => ({ title: c.title, forTeam: c.forTeam, memory: true })),+ ...fromSessions.map((f) => ({ title: f.title, forTeam: false, sessions: f.sessions.length })),]): undefined;// The picked rows that are `found`'s, which start at `from` in the list.@@@ -1745,18 -1697,37 +1822,51 @@@? undefined: async (found: T[]) => picked && picked.filter((i) => i >= from && i < from + found.length).map((i) => found[i - from]!);const learned: Note[] = [];+ const learnedFrom: Array<{ note: Note; sessions?: number }> = [];+ let sessionsRead = 0;+ // Reviews first: which of them are offered depends on the learnings already saved.+ if (reviewRead) {+ const { result, saved, kept, cancelled } = await finishReviewRead(repo, reviewRead, keepFrom<ReviewFinding>(0));+ const offered = fromReviews.length;++ pair?.phase("prs", "done", `${result.prs} PRs`, `Read ${result.prs} merged PRs: ${saved.length} thing${saved.length === 1 ? "" : "s"} reviewers made authors change`);+ if (saved.length) {+ const n = saved.length;+ const what = n < offered ? `kept ${n} of the ${offered} things` : `learned ${n} thing${n === 1 ? "" : "s"}`;+ console.error(`✓ ${what} reviewers made authors change, from the last ${result.prs} merged PRs here`);+ // saveReviewFindings keeps the findings' order.+ saved.forEach((note, i) => console.error(` for your team · from review on ${(kept[i]?.prs ?? []).map((n) => `#${n}`).join(", ")}: ${note.title}`));+ } else if (cancelled) {+ console.error(`· saved none of the ${offered} things reviewers made authors change; ${cmd("graft init")} again asks again`);+ } else if (offered) {+ console.error(`· kept none of the ${offered} things reviewers made authors change`);+ } else if (result.reason === "failed") {+ console.error(`· couldn't read PR reviews this time; ${cmd("graft init")} again tries again`);+ }+ learned.push(...saved);++ // Not said in past sessions: `sessions: 0` keeps them out of the page's session count.++ for (const note of saved) learnedFrom.push({ note, sessions: 0 });+ }+ if (memory.length) {+ const { saved, cancelled } = await finishMemoryRead(repo, memory, keepFrom<MemoryCandidate>(fromReviews.length));+ if (saved.length) {+ console.error(`✓ kept ${saved.length} of the ${memory.length} notes your Claude keeps about this repo`);+ for (const note of saved) console.error(` ${note.scope === "personal" ? "just for you " : "for your team"} · ${note.title}`);+ } else if (cancelled) {+ console.error(`· saved none of the ${memory.length} notes your Claude keeps about this repo; ${cmd("graft init")} again asks again`);+ }+ learned.push(...saved);++ for (const note of saved) learnedFrom.push({ note, sessions: 0 });+ }if (pastRead) {- const { result, saved, kept, skills, cancelled } = await finishPastRead(repo, pastRead, keepFrom<Finding>(0));- const { result, saved, kept, cancelled } = await finishPastRead(repo, pastRead, keepFrom<Finding>(fromReviews.length + memory.length));++ const { result, saved, kept, skills, cancelled } = await finishPastRead(repo, pastRead, keepFrom<Finding>(fromReviews.length + memory.length));+ sessionsRead = result.read ?? 0;+ skillsWritten = skills;+ for (const { skill, path } of skills) {+ console.error(`✓ wrote a skill from a procedure you walked Claude through more than once: ${skill.title}`);+ console.error(` ${skill.for === "team" ? "for your team" : "just for you "} · ${path}`);+ }+ if (!cancelled) for (const line of skippedSkillLines(repo, result.skills, skills)) console.error(line);+ saved.forEach((note, i) => learnedFrom.push({ note, sessions: kept[i]?.sessions.length }));const offered = result.findings.length;if (saved.length) {const n = saved.length;@@@ -1777,35 -1748,13 +1887,16 @@@}learned.push(...saved);}- if (reviewRead) {- const { result, saved, kept, cancelled } = await finishReviewRead(repo, reviewRead, keepFrom<ReviewFinding>(fromSessions.length));- const offered = result.findings.length;- pair?.phase("prs", "done", `${result.prs} PRs`, `Read ${result.prs} merged PRs: ${saved.length} thing${saved.length === 1 ? "" : "s"} reviewers flagged more than once`);- if (saved.length) {- const n = saved.length;- const what = n < offered ? `kept ${n} of the ${offered} things` : `learned ${n} thing${n === 1 ? "" : "s"}`;- console.error(`✓ ${what} reviewers flagged on more than one PR, from the last ${result.prs} merged PRs here`);- // saveReviewFindings keeps the findings' order.- saved.forEach((note, i) => console.error(` for your team · flagged in review on ${kept[i]?.prs.length ?? 2} PRs: ${note.title}`));- } else if (cancelled) {- console.error(`· saved none of the ${offered} things reviewers flagged; ${cmd("graft init")} again asks again`);- } else if (offered) {- console.error(`· kept none of the ${offered} things reviewers flagged`);- } else if (result.reason === "failed") {- console.error(`· couldn't read PR reviews this time; ${cmd("graft init")} again tries again`);- }- learned.push(...saved);- for (const note of saved) learnedFrom.push({ note, sessions: 0 });- }learnedNow = learned.length > 0;+ teamSaved = learned.filter((s) => s.scope === "repo").length;+ report?.learned?.({ notes: learnedFrom, sessions: sessionsRead });if (learnedNow) {console.error("· Claude follows them from your next session");- if (learned.some((s) => s.scope === "repo")) console.error(commitLines({}, teammatesOn(repo), "repo").uncommitted);+ if (teamSaved) console.error(commitLines({}, teammatesOn(repo), "repo").uncommitted);}}+ // Nothing read this run (already read once, or not Claude Code): the page still gets its stage.- if (!(TRAIL && (pastRead || reviewRead))) report?.learned?.({ notes: [], sessions: 0 });++ if (!(TRAIL && (pastRead || reviewRead || memory.length))) report?.learned?.({ notes: [], sessions: 0 });if (TRAIL && !learnedNow) {const home = notesHome.get(repo);if (home) {@@@ -1860,25 -1809,12 +1951,32 @@@edges: graphs.reduce((n, g) => n + g.meta.edgeCount, 0),}),);+ // Hand what was found to the review page, and leave a child waiting for+ // the person to connect and review there.+ if (pair) {+ // Teammates' branches on this person's files, checked against the+ // learnings just saved and the repo's own: synchronous, so the finding+ // exists before the page is told the read is done.+ pair.phase("team", "running", "", "Checking your team's branches");+ const teamNotes = listNotes(repo, { branches: false }).filter((n) => n.scope === "repo" && !n.ref);+ // No remote (or no default branch) means nothing was checked: `teammates`+ // is left out, since an empty list would say "checked, none".+ const teammates = teammatesChecked(repo, { learnings: teamNotes });+ pair.teamDone(teammates);+ pair.findings({ tokens, sessions: pastRead?.sessions, teammates });+ await pair.finish(repo, skillsWritten);+ pair.handOff(repo);+ console.error(`✓ Trail has what it found · review it in the browser: ${pair.url}`);+ if (!process.stdout.isTTY) console.error(`[trail] Tell the user, in one line: their Trail page has moved on; review what Trail found there. If it isn't open, the link is ${pair.url}`);+ }++ // Run by an agent, not a person: the last line tells it to ask about the+ // commit, since the person never saw the picker and Claude Code folds the rest.- if (teamSaved && !process.stderr.isTTY)++ // With --pair the person reviews them on the Trail page first, so no ask here.++ if (teamSaved && !pair && !process.stderr.isTTY)+ console.error(+ `→ ${teamSaved} team learning${teamSaved === 1 ? "" : "s"} in ${LEARNINGS_DIR}/ ${teamSaved === 1 ? "isn't" : "aren't"} committed yet. Ask the user: "Commit ${teamSaved === 1 ? "it" : `the ${teamSaved}`} so your teammates' Claude starts from ${teamSaved === 1 ? "it" : "them"}? (yes / no)"`,+ );// Sorted so `claude,cursor` and `cursor,claude` aggregate as one value.track("init_completed",diff --cc test/cli-picker.test.tsindex a207c714,8f87bdcd..45d72e88--- a/test/cli-picker.test.ts+++ b/test/cli-picker.test.ts@@@ -27,11 -27,8 +27,12 @@@ importtype PickerKey,keptLearnings,learningsPickerState,+ learningsTitle,+ displayWidth,+ drivePicker,+ renderedRows,} from '../src/cli-picker.js';+import { EventEmitter } from 'node:events';function fresh(): string { return mkdtempSync(join(tmpdir(), 'graft-picker-')); }@@@ -346,111 -343,26 +347,108 @@@ test('the rendered row shows the labelassert.match(out, /─/, 'a rule separates the settings from the agents');});- test('the learnings picker starts with every learning ticked, and enter keeps the ticked ones in order', () => {+ test("the learnings picker ticks the team's learnings, leaves the person's own unticked, and enter keeps the ticked ones in order", () => {let state = learningsPickerState([- { title: 'Use pnpm, not npm', forTeam: true, sessions: 6 },+ { title: 'Return a 500 when db.query fails', forTeam: true, prs: [41, 38] },{ title: 'Say what you understood first', forTeam: false, sessions: 4 },- { title: 'Run go test with -race', forTeam: true, sessions: 2 },+ { title: 'Run go test with -race', forTeam: true, memory: true },]);- assert.deepEqual(keptLearnings(state), [0, 1, 2]);+ assert.deepEqual(keptLearnings(state), [0, 2]);const shown = renderPicker(state, false, { title: 'keep:' });- assert.match(shown, /\[x\] Use pnpm, not npm\s+for your team · told Claude in 6 sessions/);- assert.match(shown, /\[x\] Say what you understood first\s+just for you · told Claude in 4 sessions/);+ assert.match(shown, /\[✓\] Return a 500 when db\.query fails\s+for your team · from review on PR #41, #38/);+ assert.match(shown, /\[ \] Say what you understood first\s+just for you · told Claude in 4 sessions/);+ assert.match(shown, /\[✓\] Run go test with -race\s+for your team · from your Claude's memory of this repo/);state = reducePicker(reducePicker(state, 'down'), 'space');+ assert.deepEqual(keptLearnings(state), [0, 1, 2]);+ state = reducePicker(state, 'space');assert.deepEqual(keptLearnings(state), [0, 2]);- state = reducePicker(state, 'all');- assert.deepEqual(keptLearnings(state), [0, 1, 2], 'a ticks every one back');});- test('a learning from PR reviews says how many PRs flagged it, in the same list as the session ones', () => {- const state = learningsPickerState([- { title: 'Use pnpm, not npm', forTeam: true, sessions: 6 },- { title: 'Return a 500 when db.query fails', forTeam: true, prs: 3 },- ]);- assert.deepEqual(keptLearnings(state), [0, 1]);- const shown = renderPicker(state, false, { title: 'keep:' });- assert.match(shown, /\[x\] Use pnpm, not npm\s+for your team · told Claude in 6 sessions/);- assert.match(shown, /\[x\] Return a 500 when db\.query fails\s+for your team · flagged in review on 3 PRs/);+ test("the picker's title says the team's learnings are new to teammates, or that the list is the person's own", () => {+ assert.match(learningsTitle([{ title: 'a', forTeam: true, prs: [1, 2] }, { title: 'b', forTeam: false, sessions: 2 }]), /your teammates' Claude doesn't know these yet/);+ assert.match(learningsTitle([{ title: 'b', forTeam: false, sessions: 2 }]), /you told Claude these more than once/);+ const many = renderPicker(learningsPickerState([{ title: 'a', forTeam: true, prs: [9, 8, 7, 6, 5] }]), false, { title: null });+ assert.match(many, /from review on PR #9, #8, #7 \+2/);});++/**+ * Just enough of a terminal to watch a redraw: `columns` wide, lines wrap+ * (with xterm's deferred wrap at the last column), `\n` starts a new row,+ * `ESC[nA` moves up, `ESC[0J` clears to the end of the screen, colours are+ * ignored. `screen()` is what a person would see.+ */+function terminal(columns: number) {+ const rows: string[][] = [[]];+ let row = 0;+ let col = 0;+ const at = (r: number) => (rows[r] ??= []);+ return {+ columns,+ write(s: string) {+ for (let i = 0; i < s.length; ) {+ const csi = /^\x1b\[([0-9;?]*)([A-Za-z])/.exec(s.slice(i));+ if (csi) {+ const n = Number(csi[1] || '1');+ if (csi[2] === 'A') { row = Math.max(0, row - n); col = Math.min(col, columns - 1); }+ if (csi[2] === 'J') { at(row).length = Math.min(at(row).length, col); rows.length = row + 1; }+ i += csi[0].length;+ continue;+ }+ const ch = String.fromCodePoint(s.codePointAt(i)!);+ i += ch.length;+ if (ch === '\n') { row++; col = 0; at(row); continue; }+ const w = displayWidth(ch);+ if (col + w > columns) { row++; col = 0; }+ at(row)[col] = ch;+ if (w === 2) at(row)[col + 1] = '';+ col += w;+ }+ return true;+ },+ screen(): string[] {+ return rows.map((r) => Array.from(r, (c) => c ?? ' ').join('').trimEnd());+ },+ };+}++function fakeStdin() {+ return Object.assign(new EventEmitter(), {+ isRaw: false,+ setRawMode(raw: boolean) { this.isRaw = raw; },+ resume() {},+ pause() {},+ });+}++test('renderedRows counts the rows a wrapped line takes, not just the lines', () => {+ assert.equal(renderedRows('a\nb', 80), 2);+ assert.equal(renderedRows('x'.repeat(80), 80), 1, 'exactly the width is one row');+ assert.equal(renderedRows('x'.repeat(81), 80), 2);+ assert.equal(renderedRows(`\x1b[2m${'x'.repeat(80)}\x1b[0m`, 80), 1, 'colour codes take no room');+ assert.equal(renderedRows('', 80), 1);+ assert.equal(renderedRows('漢'.repeat(41), 80), 2, 'wide characters take two columns');+});++test('in an 80-column terminal, redrawing the picker over a wrapped line leaves no copy of its title behind', async () => {+ const repo = fresh(); const home = fresh(); // nothing installed: the "+ N not detected (…)" line is long+ const state = initialPickerState(planInit(repo, { home }), repo, home);+ const text = renderPicker(state, true);+ assert.ok(text.split('\n').some((l) => displayWidth(l) > 80), 'a line wider than 80 columns, so it wraps');++ const term = terminal(80);+ term.write('$ graft init\n');+ const stdin = fakeStdin();+ const picked = drivePicker(state, undefined, { out: term, stdin });+ const titles = () => term.screen().filter((l) => l.includes('pick the agents your team uses')).length;+ assert.equal(titles(), 1);+ for (const key of ['\x1b[B', '\x1b[B', '\x1b[A', 'm', 'm', ' ']) {+ stdin.emit('data', Buffer.from(key));+ assert.equal(titles(), 1, `one title after ${JSON.stringify(key)}`);+ assert.equal(term.screen()[0], '$ graft init', 'what was above the picker stays');+ }+ stdin.emit('data', Buffer.from('\r'));+ assert.ok(await picked);+ // Done, the picker erases itself completely.+ assert.equal(titles(), 0);+ assert.deepEqual(term.screen().filter(Boolean), ['$ graft init']);+});