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
fix(cloud): upload only tracked skills, label token figures as estimates, and tidy pair output
Shrish Dwivedidabf3b5a7818
diff --git a/src/ask/ask.ts b/src/ask/ask.tsindex c11f377c..4c7aa680 100644--- a/src/ask/ask.ts+++ b/src/ask/ask.ts@@ -1527,10 +1527,15 @@ function renderAsk(r: AskResult): { body: string } | { text: string } {/** Render an {@link AskResult} as a compact markdown context pack. */export function formatAsk(r: AskResult): string {+ return formatAskWithSaved(r).text;+}++/** {@link formatAsk}, plus the tokens its pack saved (what {@link askSavedTokens} says), from the one render. */+export function formatAskWithSaved(r: AskResult): { text: string; savedTokens: number } {const out = renderAsk(r);- if ("text" in out) return out.text;+ if ("text" in out) return { text: out.text, savedTokens: 0 };const savings = askSavingsLine(r, out.body);- return (savings ? `${savings}\n\n${out.body}` : out.body) + escalationNudge(r) + "\n";+ return { text: (savings ? `${savings}\n\n${out.body}` : out.body) + escalationNudge(r) + "\n", savedTokens: savedTokens(r, out.body) };}/** Tokens this lookup's pack saved against reading the files it covers whole:diff --git a/src/cli.ts b/src/cli.tsindex e09f921f..35f43b4f 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -60,7 +60,7 @@ 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 { aboutTerms, currentSessionCost } from "./notes/session-cost.js";import { beginPastRead, finishPastRead, type Finding } from "./notes/cold-start.js";-import type { SavedSkill } from "./skills/found-skill.js";+import { skippedSkillLines, type SavedSkill } from "./skills/found-skill.js";import { beginReviewRead, finishReviewRead, type ReviewFinding } from "./notes/pr-reviews.js";import { finishPair, PairRun, validPairCode } from "./cloud/pair.js";import { currentBranch, noteAuthor, teammatesOn } from "./notes/git-facts.js";@@ -77,6 +77,7 @@ import {normalizeCode,OnboardingReporter,repoRef,+ teammatesChecked,teammatesFromGit,tokensOnOneLookup,} from "./cloud/onboarding.js";@@ -1700,7 +1701,7 @@ async function runInitCommand(dir: string, opts: InitOptions, progress?: InitProif (pair) {pair.phase("tokens", "running", "", "Measuring one lookup against reading the files");tokens = tokensOnOneLookup(repo, { contextDir: program.opts<GlobalOpts>().dir });- pair.phase("tokens", "done", tokens ? `${tokens.pct}% fewer` : "skipped", tokens ? `One lookup used ${tokens.pct}% fewer tokens than reading ${tokens.files} file${tokens.files === 1 ? "" : "s"}` : undefined);+ pair.tokensDone(tokens);}if (!verbose) {@@ -1754,6 +1755,7 @@ async function runInitCommand(dir: string, opts: InitOptions, progress?: InitProconsole.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) {@@ -1866,8 +1868,10 @@ async function runInitCommand(dir: string, opts: InitOptions, progress?: InitPro// 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);- const teammates = teammatesFromGit(repo, { learnings: teamNotes });- pair.phase("team", "done", `${teammates.length} ${teammates.length === 1 ? "person" : "people"}`);+ // 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);diff --git a/src/cloud/lookup-activity.ts b/src/cloud/lookup-activity.tsindex 1db4a1af..1aa0dd74 100644--- a/src/cloud/lookup-activity.ts+++ b/src/cloud/lookup-activity.ts@@ -19,16 +19,18 @@ function pointerFile(pointer: string): string {/*** Queue one search event for `r`, when it showed a learning or saved tokens.* Uses are counted from the learnings shown only; `saved_tokens` rides along.- * Query and files are sent only with a shown learning. Never throws.+ * Query and files are sent only with a shown learning. `savedTokens` is the+ * saving from a pack the caller already rendered (see formatAskWithSaved), so+ * the lookup isn't rendered a second time. Never throws.*/-export function recordLookup(r: AskResult, repo: string, cloud: Cloud | null = readCloud()): void {+export function recordLookup(r: AskResult, repo: string, cloud: Cloud | null = readCloud(), savedTokens?: number): void {try {// Cheapest checks first: most lookups are on a machine that isn't connected,// or in a repo outside the workspace, and must cost nothing here.const key = repoPlace(repo).key;if (!records(cloud, key)) return;const shown = r.notes ?? [];- const saved = askSavedTokens(r);+ const saved = savedTokens ?? askSavedTokens(r);if (!shown.length && saved <= 0) return;const me = noteAuthor(repo);// A lookup that showed no learning leaves with its savings only: the querydiff --git a/src/cloud/onboarding.ts b/src/cloud/onboarding.tsindex e52dbdab..a1773d75 100644--- a/src/cloud/onboarding.ts+++ b/src/cloud/onboarding.ts@@ -549,6 +549,18 @@ export function teammatesFromGit(repo: string,opts: { days?: number; now?: number; fetch?: boolean; max?: number; learnings?: Note[] } = {},): TeammateSummary[] {+ return teammatesChecked(repo, opts) ?? [];+}++/**+ * Like {@link teammatesFromGit}, but `undefined` when there was nothing to check+ * against: no origin remote, no default branch to compare with, or git failed.+ * An empty list means "checked, none"; a repo without a remote wasn't checked.+ */+export function teammatesChecked(+ repo: string,+ opts: { days?: number; now?: number; fetch?: boolean; max?: number; learnings?: Note[] } = {},+): TeammateSummary[] | undefined {try {const now = opts.now ?? Date.now();const days = opts.days ?? 14;@@ -556,7 +568,7 @@ export function teammatesFromGit(const myName = (git(repo, ["config", "user.name"]) ?? "").trim().toLowerCase();if (opts.fetch !== false && !process.env.TRAIL_NO_FETCH) fetchQuietly(repo);const cache = refreshBranches(repo, { fetch: false, now });- if (!cache.base) return [];+ if (!cache.base) return undefined;const mine = new Set(myRecentFiles(repo, me));const where = mine.size ? mine : new Set(hottestFiles(repo));const out: TeammateSummary[] = [];@@ -583,7 +595,7 @@ export function teammatesFromGit(}return out.sort((a, b) => b.pushed_at.localeCompare(a.pushed_at));} catch {- return [];+ return undefined;}}diff --git a/src/cloud/pair.ts b/src/cloud/pair.tsindex 00ebd917..b15e645e 100644--- a/src/cloud/pair.ts+++ b/src/cloud/pair.ts@@ -80,6 +80,13 @@ function foundSkillItem(checkout: string, s: SavedSkill): Record<string, unknown];}+/** "Found 3 learnings and 1 skill for your team"; the skills part is left out when there are none. */+export function foundLine(learnings: number, skills: number): string {+ const l = `${learnings} learning${learnings === 1 ? "" : "s"}`;+ const sk = `${skills} skill${skills === 1 ? "" : "s"}`;+ return `Found ${learnings === 0 && skills > 0 ? sk : skills > 0 ? `${l} and ${sk}` : l} for your team`;+}+/** The most found learnings one progress call may carry. */const FOUND_PER_CALL = 200;@@ -142,6 +149,22 @@ export class PairRun {this.send({ phases: this.phases, ...(log ? { log: [log] } : {}) });}+ /** The token step's end: the saving is an estimate (the pack against reading the files whole), and the page says so. */+ tokensDone(tokens: TokensSummary | null): void {+ this.phase(+ "tokens",+ "done",+ tokens ? `~${tokens.pct}% fewer tokens` : "skipped",+ tokens ? `One lookup used ~${tokens.pct}% fewer tokens than reading ${tokens.files} file${tokens.files === 1 ? "" : "s"} (estimate)` : undefined,+ );+ }++ /** The team step's end: `undefined` teammates means nothing was checked (no origin remote), not "none". */+ teamDone(teammates: TeammateSummary[] | undefined): void {+ if (teammates) this.phase("team", "done", `${teammates.length} ${teammates.length === 1 ? "person" : "people"}`);+ else this.phase("team", "done", "skipped", "No origin remote, so no teammates' branches to check");+ }+/** Send what init found beyond the learnings; keys left undefined (or a null `tokens`) are left out. */findings(f: PairFindings): void {const out: Record<string, unknown> = {};@@ -168,11 +191,13 @@ export class PairRun {]: [];const n = found.length;+ const m = found.filter((f) => f.kind === "skill").length;+ const learned = n - m;this.phases = this.phases.map((p) => (p.status === "done" ? p : { ...p, status: "done" as const }));this.phases = this.phases.map((p) => (p.id === "learnings" ? { ...p, count: String(n) } : p));for (let i = 0; i < Math.max(n, 1); i += FOUND_PER_CALL) {const part = found.slice(i, i + FOUND_PER_CALL);- this.send({ phases: this.phases, found: part, ...(i === 0 ? { log: [`Found ${n} learning${n === 1 ? "" : "s"} for your team`] } : {}) });+ this.send({ phases: this.phases, found: part, ...(i === 0 ? { log: [foundLine(learned, m)] } : {}) });}this.send({ done: true });return this.flush();diff --git a/src/cloud/workspace-sync.ts b/src/cloud/workspace-sync.tsindex 98073951..c2ad111e 100644--- a/src/cloud/workspace-sync.ts+++ b/src/cloud/workspace-sync.ts@@ -18,9 +18,9 @@* `_trail-sync` child does it.*/import { createHash } from "node:crypto";-import { spawn } from "node:child_process";+import { execFileSync, spawn } from "node:child_process";import { appendFileSync, existsSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";-import { basename, join, sep } from "node:path";+import { basename, join, relative, sep } from "node:path";import { graftCliPath } from "../claude/paths.js";import { readBranchCache, refreshBranches } from "../notes/branches.js";import { knownRepos, repoName, repoPlace, trailHome } from "../notes/home.js";@@ -48,13 +48,39 @@ function inside(root: string, p: string): boolean {return p === root || p.startsWith(root + sep);}+/** A SKILL.md bigger than this is not a skill, and is never sent. */+const SKILL_MAX_BYTES = 256 * 1024;++/**+ * Which of `paths` (relative to `root`) git tracks, by what `git ls-files` says,+ * so a gitignored or untracked file is not among them. Empty when `root` isn't a+ * git checkout or git fails: no skill goes up then.+ */+function trackedAmong(root: string, paths: string[]): Set<string> {+ if (paths.length === 0) return new Set();+ try {+ const out = execFileSync("git", ["--literal-pathspecs", "ls-files", "-z", "--", ...paths], {+ cwd: root,+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],+ timeout: 15_000,+ maxBuffer: 16 * 1024 * 1024,+ });+ return new Set(out.split("\0").filter(Boolean));+ } catch {+ return new Set();+ }+}+/*** The repo's skills, as the workspace takes them: each `.claude/skills/<name>/SKILL.md`- * in the working tree. Same item as the one init sends for a skill it just found- * (the server keeps one per repo and path): the body is SKILL.md without its- * frontmatter, the hash is of the whole file. A symlinked skill is read only when- * it resolves inside the checkout. A SKILL.md that can't be read or parsed is- * skipped. Skills kept in ~/.trail are never sent.+ * in the working tree that git tracks (an untracked or gitignored one isn't the+ * team's, so it stays here; no git, no skills). Same item as the one init sends+ * for a skill it just found (the server keeps one per repo and path): the body is+ * SKILL.md without its frontmatter, the hash is of the whole file. A symlinked+ * skill is read only when it resolves inside the checkout, and goes up when the+ * file it resolves to is tracked. A SKILL.md that can't be read or parsed, or is+ * over 256 KB, is skipped. Skills kept in ~/.trail are never sent.*/function skillItems(checkout: string): UploadedLearning[] {const dir = skillDirs(checkout).repo;@@ -66,13 +92,27 @@ function skillItems(checkout: string): UploadedLearning[] {} catch {return [];}- const out: UploadedLearning[] = [];+ // Each candidate that passes the cheap checks, with where its file really is.+ const candidates: Array<{ name: string; file: string; real: string }> = [];for (const name of names) {if (!SKILL_FOLDER.test(name) || OWN_SKILLS.has(name)) continue;try {const file = join(dir, name, "SKILL.md");- if (!statSync(join(dir, name)).isDirectory() || !statSync(file).isFile()) continue;- if (!inside(root, realpathSync(join(dir, name))) || !inside(root, realpathSync(file))) continue;+ if (!statSync(join(dir, name)).isDirectory()) continue;+ const st = statSync(file);+ if (!st.isFile() || st.size > SKILL_MAX_BYTES) continue;+ const real = realpathSync(file);+ if (!inside(root, realpathSync(join(dir, name))) || !inside(root, real)) continue;+ candidates.push({ name, file, real: relative(root, real).split(sep).join("/") });+ } catch {+ /* no SKILL.md here */+ }+ }+ const tracked = trackedAmong(root, [...new Set(candidates.map((c) => c.real))]);+ const out: UploadedLearning[] = [];+ for (const { name, file, real } of candidates) {+ if (!tracked.has(real)) continue;+ try {const text = readFileSync(file, "utf8");const parsed = matter(text);const d = parsed.data as Record<string, unknown>;@@ -89,7 +129,7 @@ function skillItems(checkout: string): UploadedLearning[] {hash: sha256(text),});} catch {- /* no SKILL.md, or one that can't be read or parsed */+ /* a SKILL.md that can't be read or parsed */}}return out;diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex 0be5b3ab..8f4f9336 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -3,7 +3,7 @@* `callTool` never throws — hosts get soft errors as isError content.*/import { Graft } from '../engine.js';-import { formatAsk, skeleton, formatSkeleton } from '../ask/ask.js';+import { formatAsk, formatAskWithSaved, skeleton, formatSkeleton } from '../ask/ask.js';import { formatCheckReport } from '../context/check.js';import { formatGraphCheckReport } from '../graph/check.js';import { loadGraphCached } from '../graph/load.js';@@ -262,8 +262,10 @@ async function callSingleTool(const inArg = typeof args.in === 'string' && args.in ? args.in : undefined;const r = engine.ask(root, query, { limit, source: true, full: args.full === true, in: inArg });// Same event the CLI's `ask` reports: the learnings shown and the tokens saved.- recordLookup(r, root);- return { text: formatAsk(r), isError: false };+ // One render serves both the answer and the saving the event reports.+ const { text, savedTokens } = formatAskWithSaved(r);+ recordLookup(r, root, undefined, savedTokens);+ return { text, isError: false };}case 'graft_file_api': {const file = String(args.file ?? '');diff --git a/src/skills/found-skill.ts b/src/skills/found-skill.tsindex f09ac0d6..c9fb5f96 100644--- a/src/skills/found-skill.ts+++ b/src/skills/found-skill.ts@@ -38,6 +38,30 @@ export function renderFoundSkill(s: FoundSkill): string {return `---\nname: ${name}\ndescription: ${JSON.stringify(s.title)}\nversion: 1\n---\n\n# ${s.title}\n\n${steps}\n`;}+/** The SKILL.md a skill of this name already has, in the repo or on this machine; null when there's none. */+function existingSkillFile(repo: string, name: string): string | null {+ const dirs = skillDirs(repo);+ for (const d of [dirs.repo, dirs.home]) {+ const there = join(d, name, "SKILL.md");+ if (existsSync(there)) return there;+ }+ return null;+}++/**+ * The lines init prints for found skills it didn't write because one of that+ * name already exists (in the repo or on this machine), one per skill.+ */+export function skippedSkillLines(repo: string, found: FoundSkill[], written: SavedSkill[]): string[] {+ const out: string[] = [];+ for (const skill of found) {+ const name = skillName(skill.name);+ if (!name || written.some((w) => w.skill === skill) || !existingSkillFile(repo, name)) continue;+ out.push(`· Skipped skill ${name}: one already exists.`);+ }+ return out;+}+/*** Write the skill, and return the path of its SKILL.md and whether this call* wrote it. A skill of that name the repo or this machine already has is left@@ -48,10 +72,8 @@ export function saveFoundSkill(repo: string, s: FoundSkill): { path: string; creconst name = skillName(s.name);if (!name) throw new Error("a skill needs a name");const dirs = skillDirs(repo);- for (const d of [dirs.repo, dirs.home]) {- const there = join(d, name, "SKILL.md");- if (existsSync(there)) return { path: there, created: false };- }+ const there = existingSkillFile(repo, name);+ if (there) return { path: there, created: false };if (s.for === "you") ensureRepoHome(repo);const dir = join(s.for === "you" ? dirs.home : dirs.repo, name);mkdirSync(dir, { recursive: true });diff --git a/test/activity-saved-tokens.test.ts b/test/activity-saved-tokens.test.tsindex 1ff5e9e1..018662eb 100644--- a/test/activity-saved-tokens.test.ts+++ b/test/activity-saved-tokens.test.ts@@ -14,7 +14,7 @@ process.env.DO_NOT_TRACK = "1";process.env[BRAND_ENV] = "trail";process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "saved-tokens-home-"));-const { formatAsk, askSavedTokens } = await import("../src/ask/ask.js");+const { formatAsk, formatAskWithSaved, askSavedTokens } = await import("../src/ask/ask.js");type AskResult = import("../src/ask/ask.js").AskResult;const { recordLookup } = await import("../src/cloud/lookup-activity.js");const { repoPlace } = await import("../src/notes/home.js");@@ -144,3 +144,19 @@ test("a repo outside the workspace records nothing", () => {assert.equal(c.reads(), 0);assert.equal(queued().length, 0);});++test("a lookup is rendered once: the saving comes from the pack already rendered", () => {+ reset();+ const { repo, cloud } = repoAndCloud();+ const r = resultSaving(15392);+ const expected = { text: formatAsk(r), saved: askSavedTokens(r) };+ const c = countingReads(r);+ const { text, savedTokens } = formatAskWithSaved(r);+ assert.equal(text, expected.text, "same text formatAsk gives");+ assert.equal(savedTokens, expected.saved);+ const renders = c.reads();+ assert.ok(renders > 0);+ recordLookup(r, repo, cloud, savedTokens);+ assert.equal(c.reads(), renders, "recording it renders nothing more");+ assert.equal(queued()[0].saved_tokens, 15392);+});diff --git a/test/cold-start-skills.test.ts b/test/cold-start-skills.test.tsindex 129326fb..a6b8fe85 100644--- a/test/cold-start-skills.test.ts+++ b/test/cold-start-skills.test.ts@@ -11,7 +11,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { PairRun } from "../src/cloud/pair.js";import { finishPastRead, findLearnings, saveSkills, type PastSession } from "../src/notes/cold-start.js";-import { saveFoundSkill, type FoundSkill, type SavedSkill } from "../src/skills/found-skill.js";+import { saveFoundSkill, skippedSkillLines, type FoundSkill, type SavedSkill } from "../src/skills/found-skill.js";import { getSkill, listSkills, skillDirs } from "../src/skills/skills.js";import { writeNote } from "../src/notes/notes.js";import { tmpRepo } from "./helpers.js";@@ -249,3 +249,23 @@ test("a team skill named like one the repo already has is not reported as found,const found = await pairFound(dir, [{ skill: COLLIDING, path: join(theirs, "SKILL.md"), created: false }]);assert.deepEqual(found.map((f) => f.kind), ["decision"]);});++test("a found team skill that collides with an existing one is named in one line, home or repo", () => {+ const dir = pairRepo("pair-skip-line");+ const theirs = join(dir, ".claude", "skills", "cut-a-release");+ mkdirSync(theirs, { recursive: true });+ writeFileSync(join(theirs, "SKILL.md"), "---\nname: cut-a-release\ndescription: theirs\n---\n\nSteps.\n");+ const mine = join(skillDirs(dir).home, "my-own-habit");+ mkdirSync(mine, { recursive: true });+ writeFileSync(join(mine, "SKILL.md"), "---\nname: my-own-habit\ndescription: mine\n---\n\nSteps.\n");+ const fresh: FoundSkill = { ...COLLIDING, name: "ship it", title: "Ship it" };+ const homeOne: FoundSkill = { ...COLLIDING, name: "my own habit", title: "My own habit", for: "you" };++ const written = saveSkills(dir, [COLLIDING, homeOne, fresh]);+ assert.deepEqual(written.map((w) => w.skill.name), ["ship it"]);+ assert.deepEqual(skippedSkillLines(dir, [COLLIDING, homeOne, fresh], written), [+ "· Skipped skill cut-a-release: one already exists.",+ "· Skipped skill my-own-habit: one already exists.",+ ]);+ assert.deepEqual(skippedSkillLines(dir, [fresh], written), [], "a skill this run wrote isn't reported as skipped");+});diff --git a/test/trail-pair.test.ts b/test/trail-pair.test.tsindex 5222aa21..ed9a0de6 100644--- a/test/trail-pair.test.ts+++ b/test/trail-pair.test.ts@@ -13,8 +13,9 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { BRAND_ENV } from "../src/brand.js";import { writeNote } from "../src/notes/notes.js";-import { finishPair, PairRun, validPairCode } from "../src/cloud/pair.js";-import { teammatesFromGit } from "../src/cloud/onboarding.js";+import { finishPair, foundLine, PairRun, validPairCode } from "../src/cloud/pair.js";+import { teammatesChecked, teammatesFromGit } from "../src/cloud/onboarding.js";+import { saveFoundSkill } from "../src/skills/found-skill.js";import { readCloud } from "../src/cloud/workspace.js";import { tmpRepo } from "./helpers.js";@@ -186,16 +187,56 @@ test("findings leave out what is undefined or null", async () => {assert.deepEqual(f.teammates, []);});-test("teammates absent on a repo without origin", async () => {+test("a repo without an origin remote sends findings without teammates, not an empty list", async () => {freshHome();const dir = tmpRepo("pair-no-origin");git(dir, ["init", "-q", "-b", "main"]);- assert.deepEqual(teammatesFromGit(dir), []);+ assert.equal(teammatesChecked(dir), undefined, "nothing to check against");+ assert.deepEqual(teammatesFromGit(dir), [], "the connect summary still takes a list");const t = okTrail();const run = await PairRun.start(repo(), "X4GM5OQU4NIA65ZR", { agent: "claude", version: "0.23.1", fetchImpl: t.fetch });assert.ok(run instanceof PairRun);- run.findings({ teammates: [] });+ const teammates = teammatesChecked(dir);+ run.teamDone(teammates);+ run.findings({ sessions: 2, teammates });await run.flush();- const f = progressCalls(t).find((c) => c.body.findings)!.body.findings as { teammates: unknown[] };- assert.deepEqual(f.teammates, []);+ const calls = progressCalls(t);+ const f = calls.find((c) => c.body.findings)!.body.findings as Record<string, unknown>;+ assert.equal("teammates" in f, false);+ assert.equal(f.sessions, 2);+ const team = (calls.filter((c) => c.body.phases).at(-1)!.body.phases as { id: string; count: string }[]).find((p) => p.id === "team")!;+ assert.equal(team.count, "skipped", "not '0 people', which would say it was checked");+});++test("the token step says it is an estimate", async () => {+ freshHome();+ const t = okTrail();+ const run = await PairRun.start(repo(), "X4GM5OQU4NIA65ZR", { agent: "claude", version: "0.23.1", fetchImpl: t.fetch });+ assert.ok(run instanceof PairRun);+ run.tokensDone({ question: "how Do works", symbol: "Do", saved: 15392, pack: 2048, baseline: 17440, pct: 88, files: 3 });+ await run.flush();+ const last = progressCalls(t).at(-1)!.body;+ const tokens = (last.phases as { id: string; count: string }[]).find((p) => p.id === "tokens")!;+ assert.equal(tokens.count, "~88% fewer tokens");+ assert.deepEqual(last.log, ["One lookup used ~88% fewer tokens than reading 3 files (estimate)"]);+});++test("the count line names learnings and skills apart, and pluralises", async () => {+ assert.equal(foundLine(0, 0), "Found 0 learnings for your team");+ assert.equal(foundLine(1, 0), "Found 1 learning for your team");+ assert.equal(foundLine(3, 0), "Found 3 learnings for your team");+ assert.equal(foundLine(1, 1), "Found 1 learning and 1 skill for your team");+ assert.equal(foundLine(2, 3), "Found 2 learnings and 3 skills for your team");+ assert.equal(foundLine(0, 2), "Found 2 skills for your team");++ freshHome();+ const dir = repo();+ const skill = { name: "cut a release", title: "Cut a release", for: "team" as const, steps: ["Run `npm test`", "Run `npm publish`"], sessions: ["a", "b"], quotes: [] };+ const saved = [{ skill, ...saveFoundSkill(dir, skill) }];+ const t = okTrail();+ const run = await PairRun.start(dir, "X4GM5OQU4NIA65ZR", { agent: "claude", version: "0.23.1", fetchImpl: t.fetch });+ assert.ok(run instanceof PairRun);+ await run.finish(dir, saved);+ const logs = progressCalls(t).flatMap((c) => (c.body.log as string[] | undefined) ?? []);+ assert.ok(logs.includes("Found 1 learning and 1 skill for your team"), logs.join(" | "));});diff --git a/test/workspace-sync-skills.test.ts b/test/workspace-sync-skills.test.tsindex 2ef3f6a9..31531bf2 100644--- a/test/workspace-sync-skills.test.ts+++ b/test/workspace-sync-skills.test.ts@@ -1,16 +1,19 @@/*** The repo's committed skills go up to the workspace with its learnings, so* the team page can show them. Only the working tree's `.claude/skills/`:- * never a skill kept on this machine, never one that points outside the repo.+ * never a skill kept on this machine, never one that points outside the repo,+ * and only one git tracks: not an untracked or gitignored one.*/import { test } from "node:test";import assert from "node:assert/strict";import { createHash } from "node:crypto";-import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs";+import { execFileSync } from "node:child_process";+import { mkdirSync, mkdtempSync, realpathSync, symlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { BRAND_ENV } from "../src/brand.js";import { learningsPayload } from "../src/cloud/workspace-sync.js";+import { writeNote } from "../src/notes/notes.js";import { skillDirs } from "../src/skills/skills.js";process.env.DO_NOT_TRACK = "1";@@ -31,8 +34,17 @@ author: Anirudh2. Cherry-pick the fix.`;+const git = (dir: string, ...args: string[]) => execFileSync("git", args, { cwd: dir, stdio: "ignore" });++/** A git checkout. Skills go up only once git tracks them: call `track` after writing the ones expected to. */function checkout(): string {- return mkdtempSync(join(tmpdir(), "skills-sync-repo-"));+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "skills-sync-repo-")));+ git(dir, "init", "-q", "-b", "main");+ return dir;+}++function track(dir: string): void {+ git(dir, "add", "-A", "-f");}function writeSkill(root: string, name: string, text: string): void {@@ -47,6 +59,7 @@ test("the repo's skill goes up as a skill learning, and a skill kept on this macconst dirs = skillDirs(dir);writeSkill(dirs.repo, "release-hotfix", HOTFIX);writeSkill(dirs.home, "my-private-habit", "---\ndescription: Only mine\n---\n\nSecret steps.\n");+ track(dir);const items = skillItems(dir);assert.equal(items.length, 1);@@ -65,16 +78,21 @@ test("the repo's skill goes up as a skill learning, and a skill kept on this mactest("a skill without a description is titled by its folder, and plain learnings carry no kind", () => {const dir = checkout();writeSkill(skillDirs(dir).repo, "pdf-coords", "---\nname: pdf-coords\n---\n\nUse points, not pixels.\n");+ writeNote(dir, { title: "Keep payment retries at 4", body: "## Decided\nFour retries.", author: "Sam", date: "2026-10-07", touches: [] });+ track(dir);const [s] = skillItems(dir);assert.equal(s!.title, "pdf-coords");assert.equal(s!.author, "");- assert.ok(learningsPayload(dir).every((l) => l.kind === undefined || l.kind === "skill"));+ const learning = learningsPayload(dir).filter((l) => l.path.startsWith(".trail/learnings/"));+ assert.equal(learning.length, 1, "the fixture's learning is in the payload");+ assert.equal(learning[0]!.kind, undefined);});test("editing a skill changes its hash in the payload", () => {const dir = checkout();const repo = skillDirs(dir).repo;writeSkill(repo, "release-hotfix", HOTFIX);+ track(dir);const before = skillItems(dir)[0]!;writeSkill(repo, "release-hotfix", HOTFIX + "3. Tag the release.\n");const after = skillItems(dir)[0]!;@@ -87,6 +105,7 @@ test("a SKILL.md that can't be parsed is skipped, and the others still go up", (const repo = skillDirs(dir).repo;writeSkill(repo, "broken", "---\ndescription: [unclosed\n - : :\n---\n\nbody\n");writeSkill(repo, "release-hotfix", HOTFIX);+ track(dir);const items = skillItems(dir);assert.deepEqual(items.map((i) => i.path), [".claude/skills/release-hotfix/SKILL.md"]);});@@ -102,6 +121,45 @@ test("a skill folder that points outside the repo is skipped, one that points insymlinkSync(join(outside, "stolen", "SKILL.md"), join(repo, "viafile", "SKILL.md"));writeSkill(join(dir, ".agents", "skills"), "shared", "---\ndescription: Shared across agents\n---\n\nSteps.\n");symlinkSync(join(dir, ".agents", "skills", "shared"), join(repo, "shared"), "dir");+ track(dir);assert.deepEqual(skillItems(dir).map((i) => i.path), [".claude/skills/shared/SKILL.md"]);});++test("an untracked skill is not uploaded, and a tracked one is", () => {+ const dir = checkout();+ const repo = skillDirs(dir).repo;+ writeSkill(repo, "release-hotfix", HOTFIX);+ track(dir);+ writeSkill(repo, "scratch-idea", "---\ndescription: Not committed\n---\n\nHalf-baked.\n");+ assert.deepEqual(skillItems(dir).map((i) => i.path), [".claude/skills/release-hotfix/SKILL.md"]);+ track(dir);+ assert.deepEqual(skillItems(dir).map((i) => i.path), [".claude/skills/release-hotfix/SKILL.md", ".claude/skills/scratch-idea/SKILL.md"]);+});++test("a gitignored skill is not uploaded, unless it was force-added", () => {+ const dir = checkout();+ const repo = skillDirs(dir).repo;+ writeFileSync(join(dir, ".gitignore"), ".claude/skills/ignored/\n.claude/skills/forced/\n");+ writeSkill(repo, "release-hotfix", HOTFIX);+ writeSkill(repo, "ignored", "---\ndescription: Ignored\n---\n\nKept out of git.\n");+ writeSkill(repo, "forced", "---\ndescription: Forced in\n---\n\nTracked anyway.\n");+ git(dir, "add", ".gitignore", ".claude/skills/release-hotfix");+ git(dir, "add", "-f", ".claude/skills/forced");+ assert.deepEqual(skillItems(dir).map((i) => i.path), [".claude/skills/forced/SKILL.md", ".claude/skills/release-hotfix/SKILL.md"]);+});++test("a checkout that isn't a git repo uploads no skills, and doesn't throw", () => {+ const dir = mkdtempSync(join(tmpdir(), "skills-sync-nogit-"));+ writeSkill(skillDirs(dir).repo, "release-hotfix", HOTFIX);+ assert.deepEqual(skillItems(dir), []);+});++test("a SKILL.md over 256 KB is skipped", () => {+ const dir = checkout();+ const repo = skillDirs(dir).repo;+ writeSkill(repo, "release-hotfix", HOTFIX);+ writeSkill(repo, "huge", `---\ndescription: Too big\n---\n\n${"x".repeat(256 * 1024 + 1)}\n`);+ track(dir);+ assert.deepEqual(skillItems(dir).map((i) => i.path), [".claude/skills/release-hotfix/SKILL.md"]);+});