Skip to content

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

feat(init): write a skill when past sessions repeat a procedure

Shrish Dwivedic596c313ad62
diff --git a/src/cli.ts b/src/cli.ts
index 02d94d14..e09f921f 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -60,6 +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 { 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";
@@ -1720,6 +1721,7 @@ async function runInitCommand(dir: string, opts: InitOptions, progress?: InitPro
// Under trail: what init learned from past sessions and PR reviews, where
// this repo's learnings are, and how many there already are.
let learnedNow = false;
+ let skillsWritten: SavedSkill[] = [];
if (TRAIL && (pastRead || reviewRead)) {
if (pastRead && !pastRead.done) console.error("· still reading your past sessions…");
const fromSessions = pastRead ? (await pastRead.result).findings : [];
@@ -1745,8 +1747,13 @@ async function runInitCommand(dir: string, opts: InitOptions, progress?: InitPro
const learnedFrom: Array<{ note: Note; sessions?: number }> = [];
let sessionsRead = 0;
if (pastRead) {
- const { result, saved, kept, cancelled } = await finishPastRead(repo, pastRead, keepFrom<Finding>(0));
+ const { result, saved, kept, skills, cancelled } = await finishPastRead(repo, pastRead, keepFrom<Finding>(0));
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}`);
+ }
saved.forEach((note, i) => learnedFrom.push({ note, sessions: kept[i]?.sessions.length }));
const offered = result.findings.length;
if (saved.length) {
@@ -1862,7 +1869,7 @@ async function runInitCommand(dir: string, opts: InitOptions, progress?: InitPro
const teammates = teammatesFromGit(repo, { learnings: teamNotes });
pair.phase("team", "done", `${teammates.length} ${teammates.length === 1 ? "person" : "people"}`);
pair.findings({ tokens, sessions: pastRead?.sessions, teammates });
- await pair.finish(repo);
+ 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}`);
diff --git a/src/cloud/pair.ts b/src/cloud/pair.ts
index eba96030..4fba83ba 100644
--- a/src/cloud/pair.ts
+++ b/src/cloud/pair.ts
@@ -13,9 +13,14 @@
* dropped.
*/
import { spawn } from "node:child_process";
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
import { graftCliPath } from "../claude/paths.js";
import { noteAuthor } from "../notes/git-facts.js";
import { repoName, repoPlace } from "../notes/home.js";
+import type { SavedSkill } from "../skills/found-skill.js";
+import { skillName } from "../skills/skills.js";
+import { matter } from "../util/front-matter.js";
import { newState, pickerRepos } from "./nudge.js";
import type { TeammateSummary, TokensSummary } from "./onboarding.js";
import { dropActivity, learningsPayload, syncRepo } from "./workspace-sync.js";
@@ -46,6 +51,27 @@ export interface PairFindings {
teammates?: TeammateSummary[];
}
+/** One team skill as a found item, or nothing when its file can't be read. */
+function foundSkillItem(checkout: string, s: SavedSkill): Record<string, unknown>[] {
+ let text: string;
+ try {
+ text = readFileSync(s.path, "utf8");
+ } catch {
+ return [];
+ }
+ return [
+ {
+ kind: "skill",
+ path: `.claude/skills/${skillName(s.skill.name)}/SKILL.md`,
+ title: s.skill.title,
+ author: noteAuthor(checkout),
+ body: matter(text).content.trim(),
+ hash: createHash("sha256").update(text).digest("hex"),
+ touches: [],
+ },
+ ];
+}
+
/** The most found learnings one progress call may carry. */
const FOUND_PER_CALL = 200;
@@ -117,13 +143,21 @@ export class PairRun {
this.send({ findings: out });
}
- /** Hand over the repo's learnings for review, then say the read is done. */
- finish(repo: string): Promise<void> {
+ /**
+ * Hand over the repo's learnings, and the skills init just wrote for the
+ * team, for review, then say the read is done. A learning is a `decision`;
+ * a skill is a `skill`. A skill kept for the person alone isn't the team's
+ * to review, so it stays off the page.
+ */
+ finish(repo: string, skills: SavedSkill[] = []): Promise<void> {
const place = repoPlace(repo);
- const found = place.git
- ? learningsPayload(place.checkout)
- .filter((l) => l.ref === "")
- .map((l) => ({ path: l.path, title: l.title, author: l.author, body: l.body, hash: l.hash, touches: l.touches }))
+ const found: Record<string, unknown>[] = place.git
+ ? [
+ ...learningsPayload(place.checkout)
+ .filter((l) => l.ref === "")
+ .map((l) => ({ kind: "decision", path: l.path, title: l.title, author: l.author, body: l.body, hash: l.hash, touches: l.touches })),
+ ...skills.filter((s) => s.skill.for === "team").flatMap((s) => foundSkillItem(place.checkout, s)),
+ ]
: [];
const n = found.length;
this.phases = this.phases.map((p) => (p.status === "done" ? p : { ...p, status: "done" as const }));
diff --git a/src/notes/cold-start.ts b/src/notes/cold-start.ts
index c92b63ef..5f234195 100644
--- a/src/notes/cold-start.ts
+++ b/src/notes/cold-start.ts
@@ -20,6 +20,8 @@ import { track } from "../telemetry/track.js";
import { readJson, writeJsonAtomic } from "../util/state.js";
import { noteAuthor } from "./git-facts.js";
import { ensureRepoHome } from "./home.js";
+import { saveFoundSkill, type FoundSkill, type SavedSkill } from "../skills/found-skill.js";
+import { OWN_SKILLS, skillName } from "../skills/skills.js";
import { mentionedFiles, shortDate, writeNote, type Note } from "./notes.js";
import { claudeProjectDir } from "./session-cost.js";
@@ -57,6 +59,8 @@ export interface FindResult {
/** How many of them, newest first, Claude read. */
read: number;
findings: Finding[];
+ /** Procedures the person walked Claude through in 2+ sessions, at most {@link MAX_SKILLS}. */
+ skills: FoundSkill[];
model: string;
durationMs: number;
costUsd?: number;
@@ -69,6 +73,7 @@ export const COLD_START_MODEL = "claude-sonnet-5-5";
/** About 80k tokens of messages: every session assign has, and newest first past that. */
const DIGEST_CHARS = 320_000;
const PROMPT_CHARS = 1200;
+const MAX_SKILLS = 2;
const BEFORE_CHARS = 240;
/* -------------------------------------------------------------------------- */
@@ -286,7 +291,22 @@ For each finding:
- body: 2 to 5 lines of markdown under "## Decided" (the rule, and why when the messages say why), plus "## Watch out" only when there's a real trap. Plain words, written to the next session. Call the person "the user", never he or she. Leave out insults and swearing, even when the messages have them. Nothing secret: no tokens, passwords, keys, email addresses or customer names.
- evidence: 2 to 4 items, each the session id from the "=== session <id>" header and a quote copied exactly from a [user] line in that session, 4 to 20 words.
-Return an empty list when nothing comes up in two sessions. Fewer good findings beat more weak ones.`;
+Return an empty list when nothing comes up in two sessions. Fewer good findings beat more weak ones.
+
+Separately, return at most 2 skills. A skill is a procedure of 2 or more steps that the person walked the agent through in 2 or more different sessions, in the same order each time (cutting a release, regenerating a fixture, deploying to staging). It is not a rule or a preference; those are findings. For each skill:
+- name: a verb phrase of 2 to 5 words, like "cut a release".
+- title: under 60 characters, what the procedure does, in plain words.
+- for: "team" when anyone working in the repo would follow it; "you" when it is about this person's own machine or habits.
+- steps: 2 to 8 items in order, each a command or an action, written to the next session. Nothing secret: no tokens, passwords, keys, email addresses or customer names. Call the person "the user".
+- evidence: 2 to 4 items, each the session id from the "=== session <id>" header and a quote copied exactly from a [user] line in that session where they walked the agent through it, 4 to 20 words.
+Return an empty skills list when no procedure came up in two sessions.`;
+
+const EVIDENCE = {
+ type: "object",
+ properties: { session: { type: "string" }, quote: { type: "string" } },
+ required: ["session", "quote"],
+ additionalProperties: false,
+} as const;
const SCHEMA = {
type: "object",
@@ -299,22 +319,29 @@ const SCHEMA = {
title: { type: "string" },
for: { type: "string", enum: ["team", "you"] },
body: { type: "string" },
- evidence: {
- type: "array",
- items: {
- type: "object",
- properties: { session: { type: "string" }, quote: { type: "string" } },
- required: ["session", "quote"],
- additionalProperties: false,
- },
- },
+ evidence: { type: "array", items: EVIDENCE },
},
required: ["title", "for", "body", "evidence"],
additionalProperties: false,
},
},
+ skills: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: { type: "string" },
+ title: { type: "string" },
+ for: { type: "string", enum: ["team", "you"] },
+ steps: { type: "array", items: { type: "string" }, minItems: 2, maxItems: 8 },
+ evidence: { type: "array", items: EVIDENCE, minItems: 2, maxItems: 4 },
+ },
+ required: ["name", "title", "for", "steps", "evidence"],
+ additionalProperties: false,
+ },
+ },
},
- required: ["findings"],
+ required: ["findings", "skills"],
additionalProperties: false,
} as const;
@@ -325,6 +352,14 @@ interface RawFinding {
evidence?: { session?: string; quote?: string }[];
}
+interface RawSkill {
+ name?: string;
+ title?: string;
+ for?: string;
+ steps?: string[];
+ evidence?: { session?: string; quote?: string }[];
+}
+
/** Whether `claude` (Claude Code) is on PATH. */
function claudeOnPath(): boolean {
const r = spawnSync("claude", ["--version"], { stdio: "ignore", timeout: 10_000 });
@@ -378,7 +413,8 @@ export function hasClaude(home?: string): boolean {
* shows up as a past session), from a scratch folder so no repo's CLAUDE.md or
* hooks load. `TRAIL_NO_HOOKS` keeps trail's own user-level hooks quiet too.
* Past sessions by default; the PR review read brings its own system prompt
- * and schema, with `findings` at the top.
+ * and schema, with `findings` at the top. `skills` comes back when the schema
+ * has them.
*/
export function askClaude<T = RawFinding>(
bin: string,
@@ -386,7 +422,7 @@ export function askClaude<T = RawFinding>(
model: string,
timeoutMs: number,
ask: { system: string; schema: object } = { system: SYSTEM, schema: SCHEMA },
-): Promise<{ findings: T[]; costUsd?: number } | null> {
+): Promise<{ findings: T[]; skills: RawSkill[]; costUsd?: number } | null> {
return new Promise((done) => {
const args = [
"-p",
@@ -416,9 +452,9 @@ export function askClaude<T = RawFinding>(
child.on("close", () => {
clearTimeout(timer);
try {
- const r = JSON.parse(out) as { is_error?: boolean; structured_output?: { findings?: T[] }; total_cost_usd?: number };
+ const r = JSON.parse(out) as { is_error?: boolean; structured_output?: { findings?: T[]; skills?: RawSkill[] }; total_cost_usd?: number };
if (r.is_error || !r.structured_output) return done(null);
- done({ findings: r.structured_output.findings ?? [], costUsd: r.total_cost_usd });
+ done({ findings: r.structured_output.findings ?? [], skills: r.structured_output.skills ?? [], costUsd: r.total_cost_usd });
} catch {
done(null);
}
@@ -498,6 +534,35 @@ export function verify(raw: RawFinding[], sessions: PastSession[], ids: Map<stri
return out.sort((a, b) => b.sessions.length - a.sessions.length || b.last.localeCompare(a.last));
}
+/**
+ * The skills whose quotes are really in the person's messages, in two or more
+ * sessions, at most {@link MAX_SKILLS}, the ones said in the most sessions
+ * first. A skill needs a name, 2 to 8 steps and a place that's its own (not
+ * trail's or graft's skill); its title and steps are scrubbed.
+ */
+export function verifySkills(raw: RawSkill[], sessions: PastSession[], ids: Map<string, string>): FoundSkill[] {
+ const sources = sessions.map((s) => ({ id: s.id, at: s.at, said: s.prompts.map((p) => norm(p.text)) }));
+ const byId = new Map(sources.map((x) => [x.id, x]));
+ const out: FoundSkill[] = [];
+ const seen = new Set<string>();
+ for (const f of raw) {
+ const title = scrub(f.title?.replace(/\s+/g, " ").trim() ?? "").slice(0, 80);
+ const name = skillName(f.name?.trim() || title);
+ if (!title || !name || OWN_SKILLS.has(name) || seen.has(name)) continue;
+ const steps = (f.steps ?? [])
+ .map((s) => scrub((typeof s === "string" ? s : "").replace(/\s*\n\s*/g, " ").replace(/^\s*(?:\d+[.)]|[-*])\s+/, "").trim()))
+ .filter(Boolean);
+ if (steps.length < 2 || steps.length > 8) continue;
+ const evidence = (f.evidence ?? []).map((ev) => ({ cited: byId.get(ids.get(ev.session?.trim() ?? "") ?? ""), quote: ev.quote }));
+ const { places, quotes } = placeQuotes(evidence, sources);
+ if (places.length < 2) continue;
+ seen.add(name);
+ out.push({ name, title, for: f.for === "you" ? "you" : "team", steps, sessions: places.map((s) => s.id), quotes });
+ }
+ const last = (s: FoundSkill) => sources.find((x) => x.id === s.sessions[0])?.at ?? "";
+ return out.sort((a, b) => b.sessions.length - a.sessions.length || last(b).localeCompare(last(a))).slice(0, MAX_SKILLS);
+}
+
/** Anything that looks like a credential, a key or an email address, replaced. Learnings get committed. */
export function scrub(text: string): string {
return text
@@ -527,7 +592,7 @@ export async function findLearnings(
const model = opts.model ?? COLD_START_MODEL;
const started = Date.now();
const sessions = opts.sessions ?? pastSessions(repo, opts.home);
- const base = { sessions: sessions.length, read: 0, model, findings: [] as Finding[] };
+ const base = { sessions: sessions.length, read: 0, model, findings: [] as Finding[], skills: [] as FoundSkill[] };
if (sessions.length < 2) return { ...base, durationMs: Date.now() - started, reason: "no_sessions" };
const bin = claudeBin(opts.home);
if (!bin) return { ...base, durationMs: Date.now() - started, reason: "no_claude" };
@@ -535,14 +600,15 @@ export async function findLearnings(
base.read = ids.size;
const asked = await askClaude(
bin,
- `Past sessions in this repository, newest first. Find what the person had to tell the agent more than once.\n\n${text}`,
+ `Past sessions in this repository, newest first. Find what the person had to tell the agent more than once, and any procedure they walked the agent through in more than one session.\n\n${text}`,
model,
opts.timeoutMs ?? 180_000,
);
const durationMs = Date.now() - started;
if (!asked) return { ...base, durationMs, reason: "failed" };
const findings = verify(asked.findings, sessions, ids).slice(0, opts.limit ?? 5);
- return { ...base, findings, durationMs, costUsd: asked.costUsd, reason: findings.length ? undefined : "none_found" };
+ const skills = verifySkills(asked.skills, sessions, ids);
+ return { ...base, findings, skills, durationMs, costUsd: asked.costUsd, reason: findings.length || skills.length ? undefined : "none_found" };
}
/* -------------------------------------------------------------------------- */
@@ -603,6 +669,19 @@ export function saveFindings(repo: string, findings: Finding[], author = noteAut
);
}
+/** Each found skill as a SKILL.md: the team's in the repo, the person's own in ~/.trail. One that can't be written is skipped. */
+export function saveSkills(repo: string, skills: FoundSkill[]): SavedSkill[] {
+ const out: SavedSkill[] = [];
+ for (const skill of skills) {
+ try {
+ out.push({ skill, path: saveFoundSkill(repo, skill) });
+ } catch {
+ /* read-only checkout, say: the learnings still saved */
+ }
+ }
+ return out;
+}
+
/**
* Wait for the read, save the findings the person keeps, and remember the repo
* was read. Every finding is kept unless `keep` picks; `keep` resolving null
@@ -612,13 +691,16 @@ export async function finishPastRead(
repo: string,
read: PastRead,
keep?: (findings: Finding[]) => Promise<Finding[] | null>,
-): Promise<{ result: FindResult; saved: Note[]; kept: Finding[]; cancelled: boolean }> {
+): Promise<{ result: FindResult; saved: Note[]; kept: Finding[]; skills: SavedSkill[]; cancelled: boolean }> {
const result = await read.result;
const chosen = result.findings.length && keep ? await keep(result.findings) : result.findings;
const kept = chosen ?? [];
const saved = kept.length ? saveFindings(repo, kept) : [];
- const outcome = chosen === null ? "cancelled" : result.findings.length ? "found" : (result.reason ?? "none_found");
- if (outcome === "found" || outcome === "none_found") writeJsonAtomic(readMark(repo), { at: Date.now(), model: result.model, saved: saved.length }, true);
+ // Skills aren't in the pick: they're written unless the person cancelled, and never over one that exists.
+ const skills = chosen === null ? [] : saveSkills(repo, result.skills);
+ const found = result.findings.length > 0 || result.skills.length > 0;
+ const outcome = chosen === null ? "cancelled" : found ? "found" : (result.reason ?? "none_found");
+ if (outcome === "found" || outcome === "none_found") writeJsonAtomic(readMark(repo), { at: Date.now(), model: result.model, saved: saved.length, skills: skills.length }, true);
track(
"cold_start",
{
@@ -632,5 +714,5 @@ export async function finishPastRead(
},
{ repo },
);
- return { result, saved, kept, cancelled: chosen === null };
+ return { result, saved, kept, skills, cancelled: chosen === null };
}
diff --git a/src/skills/found-skill.ts b/src/skills/found-skill.ts
new file mode 100644
index 00000000..a658a1b3
--- /dev/null
+++ b/src/skills/found-skill.ts
@@ -0,0 +1,58 @@
+/**
+ * A skill found in past sessions: a procedure the person walked Claude through
+ * in two or more of them, written to a SKILL.md at `trail init` so the next
+ * session can follow it without being walked through it again.
+ *
+ * The team's go in the repo's `.claude/skills/`, where Claude Code loads them
+ * for everyone who pulls; the person's own go in this repo's skills under
+ * ~/.trail. A skill of that name that already exists is never touched.
+ */
+import { existsSync, mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { ensureRepoHome } from "../notes/home.js";
+import { skillDirs, skillName } from "./skills.js";
+
+export interface FoundSkill {
+ name: string;
+ title: string;
+ /** `team`: written into the repo. `you`: kept on this machine. */
+ for: "team" | "you";
+ /** What to do, in order: 2 to 8 commands or actions. */
+ steps: string[];
+ /** Sessions the cited quotes were found in, newest first. */
+ sessions: string[];
+ quotes: string[];
+}
+
+/** A skill as written: where its SKILL.md is, whether this run wrote it or it was there already. */
+export interface SavedSkill {
+ skill: FoundSkill;
+ path: string;
+}
+
+/** SKILL.md for a found skill: the frontmatter every skill has, then its steps as a numbered list. */
+export function renderFoundSkill(s: FoundSkill): string {
+ const name = skillName(s.name);
+ const steps = s.steps.map((step, i) => `${i + 1}. ${step}`).join("\n");
+ return `---\nname: ${name}\ndescription: ${JSON.stringify(s.title)}\nversion: 1\n---\n\n# ${s.title}\n\n${steps}\n`;
+}
+
+/**
+ * Write the skill, and return the path of its SKILL.md. A skill of that name
+ * the repo or this machine already has is left as it is: its path comes back.
+ */
+export function saveFoundSkill(repo: string, s: FoundSkill): string {
+ const 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 there;
+ }
+ if (s.for === "you") ensureRepoHome(repo);
+ const dir = join(s.for === "you" ? dirs.home : dirs.repo, name);
+ mkdirSync(dir, { recursive: true });
+ const file = join(dir, "SKILL.md");
+ writeFileSync(file, renderFoundSkill(s));
+ return file;
+}
diff --git a/src/skills/skills.ts b/src/skills/skills.ts
index 2f1c9a89..1de5304a 100644
--- a/src/skills/skills.ts
+++ b/src/skills/skills.ts
@@ -24,7 +24,7 @@ import { shortDate, slug } from "../notes/notes.js";
import { ensureRepoHome, repoPlace } from "../notes/home.js";
/** Trail's and graft's own skills, rewritten by every `init`: never a place for takeaways. */
-const OWN_SKILLS = new Set(["trail", "graft"]);
+export const OWN_SKILLS =new Set(["trail", "graft"]);
/** Where a repo's skills are: the team's in the repo, and this machine's in ~/.trail. */
export function skillDirs(dir: string): { repo: string; home: string } {
diff --git a/test/cold-start-skills.test.ts b/test/cold-start-skills.test.ts
new file mode 100644
index 00000000..eb792107
--- /dev/null
+++ b/test/cold-start-skills.test.ts
@@ -0,0 +1,190 @@
+/**
+ * Day-one skills: a procedure the person walked Claude through in two or more
+ * past sessions becomes a skill, with the same two-session quote check a
+ * learning gets. Claude Code is a stand-in `claude` on PATH, as in the init test.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { PairRun } from "../src/cloud/pair.js";
+import { finishPastRead, findLearnings, type PastSession } from "../src/notes/cold-start.js";
+import { saveFoundSkill, type FoundSkill } 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";
+
+function session(id: string, at: string, ...texts: string[]): PastSession {
+ return { id, at, prompts: texts.map((text) => ({ text })) };
+}
+
+const STEPS = ["Run `npm run build`", "Run `npm test`", "Bump the version in package.json", "Run `npm publish --otp` with the code from the user"];
+
+const sessions = [
+ session("aaaaaaaa-1", "2026-10-09T00:00:00Z", "ok now cut the release: build, test, bump the version, then publish"),
+ session("bbbbbbbb-2", "2026-10-01T00:00:00Z", "cut the release the usual way: build, test, bump the version, publish"),
+ session("cccccccc-3", "2026-09-20T00:00:00Z", "something else entirely"),
+];
+
+const quotes = (a = "aaaaaaaa", b = "bbbbbbbb") => [
+ { session: a, quote: "cut the release: build, test, bump the version" },
+ { session: b, quote: "cut the release the usual way: build, test, bump the version" },
+];
+
+function rawSkill(over: object = {}) {
+ return { name: "cut a release", title: "Cut a release", for: "team", steps: STEPS, evidence: quotes(), ...over };
+}
+
+/** A `claude` that answers --version, and answers -p with `skills` and no findings. */
+function fakeClaude(skills: object[]): string {
+ const bin = mkdtempSync(join(tmpdir(), "fake-claude-skills-"));
+ const answer = { is_error: false, total_cost_usd: 0.01, structured_output: { findings: [], skills } };
+ writeFileSync(
+ join(bin, "claude"),
+ `#!/usr/bin/env node\nif (process.argv.includes("--version")) { console.log("9.9.9"); process.exit(0); }\nprocess.stdin.resume(); process.stdin.on("end", () => console.log(${JSON.stringify(JSON.stringify(answer))}));\n`,
+ );
+ chmodSync(join(bin, "claude"), 0o755);
+ return bin;
+}
+
+/** Run `fn` with a fresh TRAIL_HOME and the stand-in claude first on PATH. */
+async function withClaude<T>(skills: object[], fn: (repo: string) => Promise<T>): Promise<T> {
+ const env = { TRAIL_HOME: process.env.TRAIL_HOME, DO_NOT_TRACK: process.env.DO_NOT_TRACK, PATH: process.env.PATH };
+ process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "skills-home-"));
+ process.env.DO_NOT_TRACK = "1";
+ process.env.PATH = `${fakeClaude(skills)}:${process.env.PATH}`;
+ try {
+ const repo = tmpRepo("found-skill");
+ spawnSync("git", ["init", "-q"], { cwd: repo });
+ return await fn(repo);
+ } finally {
+ process.env.TRAIL_HOME = env.TRAIL_HOME;
+ process.env.DO_NOT_TRACK = env.DO_NOT_TRACK;
+ process.env.PATH = env.PATH;
+ }
+}
+
+async function readAndFinish(repo: string) {
+ const result = await findLearnings(repo, { sessions });
+ const done = await finishPastRead(repo, { sessions: sessions.length, started: Date.now(), done: true, result: Promise.resolve(result) });
+ return { result, done };
+}
+
+// The stand-in for Claude Code is a shebang script, which Windows won't run as `claude`.
+const posix = { skip: process.platform === "win32" };
+
+test("a skill quoted in two sessions is saved to the repo as a SKILL.md the skills list reads", posix, async () => {
+ await withClaude([rawSkill()], async (repo) => {
+ const { result, done } = await readAndFinish(repo);
+ assert.equal(result.skills.length, 1);
+ assert.deepEqual(result.skills[0]!.sessions, ["aaaaaaaa-1", "bbbbbbbb-2"]);
+ const file = join(repo, ".claude", "skills", "cut-a-release", "SKILL.md");
+ assert.deepEqual(done.skills.map((s) => s.path), [file]);
+ const text = readFileSync(file, "utf8");
+ assert.match(text, /^---\nname: cut-a-release\n/);
+ assert.match(text, /\n1\. Run `npm run build`\n2\. Run `npm test`\n3\. Bump the version in package.json\n4\. Run /);
+ const skill = getSkill(repo, "cut-a-release")!;
+ assert.equal(skill.where, "repo");
+ assert.equal(skill.description, "Cut a release");
+ assert.deepEqual(listSkills(repo).map((s) => s.name), ["cut-a-release"]);
+ });
+});
+
+test("a skill quoted from one session is dropped", posix, async () => {
+ await withClaude([rawSkill({ evidence: [quotes()[0]!, { session: "aaaaaaaa", quote: "ok now cut the release: build, test" }] })], async (repo) => {
+ const { result, done } = await readAndFinish(repo);
+ assert.deepEqual(result.skills, []);
+ assert.deepEqual(done.skills, []);
+ assert.equal(existsSync(join(repo, ".claude", "skills")), false);
+ });
+});
+
+test("a skill with made-up quotes, under two steps, or named like trail's own is dropped", posix, async () => {
+ const bad = [
+ rawSkill({ name: "made up", evidence: [{ session: "aaaaaaaa", quote: "never said anything like this" }, { session: "bbbbbbbb", quote: "nor this one either" }] }),
+ rawSkill({ name: "one step", steps: ["Run `npm test`"] }),
+ rawSkill({ name: "trail" }),
+ rawSkill({ name: "" , title: ""}),
+ ];
+ await withClaude(bad, async (repo) => {
+ const { result } = await readAndFinish(repo);
+ assert.deepEqual(result.skills, []);
+ });
+});
+
+test("a skill for you is written to this machine's skills, not the repo", posix, async () => {
+ await withClaude([rawSkill({ for: "you" })], async (repo) => {
+ const { done } = await readAndFinish(repo);
+ const home = join(skillDirs(repo).home, "cut-a-release", "SKILL.md");
+ assert.deepEqual(done.skills.map((s) => s.path), [home]);
+ assert.equal(existsSync(home), true);
+ assert.equal(existsSync(join(repo, ".claude")), false, "nothing in the repo");
+ assert.equal(getSkill(repo, "cut-a-release")!.where, "home");
+ });
+});
+
+test("at most 2 skills come back, the ones in the most sessions first, with secrets scrubbed from the steps", posix, async () => {
+ const many = [
+ rawSkill({ name: "one", steps: ["Export `api_key=sk-abcdefghijklmnopqrstuv`", "Run `npm test`"], evidence: quotes() }),
+ rawSkill({ name: "two" }),
+ rawSkill({ name: "three" }),
+ ];
+ await withClaude(many, async (repo) => {
+ const { result } = await readAndFinish(repo);
+ assert.equal(result.skills.length, 2);
+ assert.doesNotMatch(result.skills[0]!.steps.join("\n"), /sk-abcdef/);
+ assert.match(result.skills[0]!.steps.join("\n"), /\[redacted\]/);
+ });
+});
+
+test("saving a skill never overwrites one of that name, the team's or this machine's", () => {
+ process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "skills-nooverwrite-"));
+ const repo = tmpRepo("found-skill-keep");
+ spawnSync("git", ["init", "-q"], { cwd: repo });
+ const found: FoundSkill = { name: "cut a release", title: "Cut a release", for: "team", steps: STEPS, sessions: ["a", "b"], quotes: [] };
+ const theirs = join(repo, ".claude", "skills", "cut-a-release");
+ mkdirSync(theirs, { recursive: true });
+ writeFileSync(join(theirs, "SKILL.md"), "---\nname: cut-a-release\ndescription: theirs\n---\n\nTheirs.\n");
+ assert.equal(saveFoundSkill(repo, found), join(theirs, "SKILL.md"));
+ assert.match(readFileSync(join(theirs, "SKILL.md"), "utf8"), /Theirs\./);
+ // The same name for you finds the team's, and leaves it be.
+ assert.equal(saveFoundSkill(repo, { ...found, for: "you" }), join(theirs, "SKILL.md"));
+ // Saved once for you, the second save returns the first's path.
+ const other: FoundSkill = { ...found, name: "ship it", for: "you" };
+ const first = saveFoundSkill(repo, other);
+ writeFileSync(first, "edited by hand");
+ assert.equal(saveFoundSkill(repo, other), first);
+ assert.equal(readFileSync(first, "utf8"), "edited by hand");
+});
+
+test("init --pair hands over found items with a kind: learnings are decisions, skills are skills", async () => {
+ process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "skills-pair-"));
+ process.env.DO_NOT_TRACK = "1";
+ process.env.TRAIL_URL = "http://trail.test";
+ const dir = tmpRepo("pair-skill");
+ spawnSync("git", ["init", "-q", "-b", "main"], { cwd: dir });
+ spawnSync("git", ["remote", "add", "origin", "https://github.com/acme/billing.git"], { cwd: dir });
+ writeNote(dir, { title: "Keep payment retries at 4", body: "## Decided\nFour retries.", author: "Sam", date: "2026-10-07", touches: [] });
+ const team: FoundSkill = { name: "cut a release", title: "Cut a release", for: "team", steps: STEPS, sessions: ["a", "b"], quotes: [] };
+ const mine: FoundSkill = { name: "my own habit", title: "My own habit", for: "you", steps: STEPS, sessions: ["a", "b"], quotes: [] };
+ const saved = [team, mine].map((skill) => ({ skill, path: saveFoundSkill(dir, skill) }));
+
+ const calls: { path: string; body: Record<string, unknown> }[] = [];
+ const fetchImpl = (async (url: string | URL, init?: RequestInit) => {
+ const u = new URL(String(url));
+ calls.push({ path: u.pathname, body: init?.body ? JSON.parse(String(init.body)) : {} });
+ return u.pathname === "/api/cli/handoffs" ? new Response(JSON.stringify({ url: "http://trail.test/c" }), { status: 201 }) : new Response("{}", { status: 202 });
+ }) as typeof fetch;
+ const run = await PairRun.start(dir, "X4GM5OQU4NIA65ZR", { agent: "claude", version: "0.23.1", fetchImpl });
+ assert.ok(run instanceof PairRun);
+ await run.finish(dir, saved);
+
+ const found = calls.filter((c) => c.path === "/api/cli/handoffs/progress").flatMap((c) => (c.body.found as Record<string, unknown>[] | undefined) ?? []);
+ assert.deepEqual(found.map((f) => [f.kind, f.title]), [["decision", "Keep payment retries at 4"], ["skill", "Cut a release"]]);
+ const skill = found[1]!;
+ assert.equal(skill.path, ".claude/skills/cut-a-release/SKILL.md");
+ assert.match(String(skill.body), /1\. Run `npm run build`/);
+ assert.equal(typeof skill.hash, "string");
+});
diff --git a/test/trail-cold-start.test.ts b/test/trail-cold-start.test.ts
index af6616b7..330ae71e 100644
--- a/test/trail-cold-start.test.ts
+++ b/test/trail-cold-start.test.ts
@@ -309,7 +309,7 @@ function found(title: string, forWho: "team" | "you"): Finding {
}
function readWith(findings: Finding[]) {
- const result: FindResult = { sessions: 3, read: 3, findings, model: "claude-sonnet-5-5", durationMs: 10 };
+ const result: FindResult = { sessions: 3, read: 3, findings, skills: [], model: "claude-sonnet-5-5", durationMs: 10 };
return { sessions: 3, started: Date.now(), done: true, result: Promise.resolve(result) };
}