Skip to content

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

Merge main's learned skills into release/0.24.1

Shrish Dwivedi1bb17dd5aa1c
diff --cc src/cli.ts
index e5eef5e3,c691d879..fed0b646
--- a/src/cli.ts
+++ b/src/cli.ts
@@@ -47,9 -48,8 +48,9 @@@ import
import { formatInitEpilogue } from "./cli-epilogue.js";
import { planInit, selectedWrites } from "./hosts/plan.js";
import { planRetract, runRetract, changed, type Retraction } from "./hosts/retract.js";
- import { compactWrites, formatNonInteractiveHelp, formatPlan, pickLearnings, runPicker } from "./cli-picker.js";
+ import { compactWrites, formatNonInteractiveHelp, formatPlan, runPicker } from "./cli-picker.js";
import { buildGraphWithProgress } from "./claude/build-progress.js";
+import { installBrainsServer, removeBrainsServer } from "./hosts/claude-global.js";
import { homedir } from "node:os";
import { formatUpgradeReport, formatVersionReport, getNpmViewVersion, readCurrentVersion, readPackageName, runUpgrade } from "./cli-meta.js";
import { nativeFallbackNotice } from "./graph/native.js";
@@@ -57,36 -57,23 +58,38 @@@ import { patchBuildConfig, type BuildCo
import { normalizePathPrefix } from "./util/paths.js";
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 { costLabel, listNotes, noteName, notePlace, noteTargets, readingTokens, 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 { skippedSkillLines, type SavedSkill } from "./skills/found-skill.js";
- import { anchoredReviews, beginReviewRead, finishReviewRead, type ReviewFinding } from "./notes/pr-reviews.js";
- import { finishMemoryRead, memoryCandidates, offeredBefore, type MemoryCandidate } from "./notes/memory-notes.js";
+ import { flatLine, unmarkedWords } from "./notes/flatten.js";
+ import { beginLookBack, finishLookBack } from "./init/run.js";
+ import { keepCommand } from "./init/keep.js";
+ import { recordInit, snapInit } from "./init/install-paths.js";
+import { finishPair, PairRun, validPairCode } from "./cloud/pair.js";
import { currentBranch, noteAuthor, teammatesOn } from "./notes/git-facts.js";
+ import { listSkills } from "./skills/skills.js";
+ import { registerSkillCommands } from "./skills/cli-skills.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, trailUrl, writeCloud, type Cloud } from "./cloud/workspace.js";
-import { addRepo, clearCloud, cloudEnabled, fetchMe, fetchTeam, isError, readCloud, serverUrl, writeCloud, type Cloud } from "./cloud/workspace.js";
++import { addRepo, clearCloud, cloudEnabled, fetchMe, fetchTeam, isError, readCloud, serverUrl, trailUrl, useServer, 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 { inWorkspace, maybeSyncInBackground, recordActivity, runSyncChild, syncRepo, workspaceLearnings } from "./cloud/workspace-sync.js";
import type { CheckResult } from "./check/types.js";
import { checkLocally } from "./check/local-check.js";
+ import { findLearning, liveLearnings } from "./notes/learning-fields.js";
+ import { savedIdLine } from "./notes/replace.js";
import { formatOverlap, maybeRefreshBranches, overlapsWith, pushedWhen, readBranchCache, refreshBranches } from "./notes/branches.js";
import { ensureRepoTrail, LEARNINGS_DIR } from "./notes/repo-trail.js";
import type { AskResult } from "./ask/ask.js";
@@@ -372,15 -345,6 +361,18 @@@ progra
await waitForConnect();
});
+program
+ .command("_trail-pair", { hidden: true })
+ .description("internal: after `init --pair`, wait for the connect and the review in the browser, then upload the repo's learnings")
+ .argument("<state>")
+ .argument("<dir>")
- .action(async (state: string, dir: string) => {
++ .argument("[server]", "the Trail the run reported to (init's --server)")
++ .action(async (state: string, dir: string, server?: string) => {
++ const base = serverUrl(server);
++ if (base) useServer(base);
+ await finishPair(state, resolve(dir));
+ });
+
program
.command("_update-check", { hidden: true })
.description("internal: refresh the cached latest-version answer")
@@@ -779,8 -744,20 +771,6 @@@ function afterAsk(r: AskResult, repo: s
const shown = r.notes ?? [];
if (shown.length) {
for (const h of shown) h.note.teammate = !!h.note.author && !!me && h.note.author !== me;
- const saved = shown.reduce((sum, h) => sum + savedByNote(h.note), 0);
- track("learning_reused", { teammate: String(shown.some((h) => h.note.teammate)), saved_tokens_bucket: savedTokensBucket(saved) }, { repo });
- // Only learnings the workspace gets: a personal one's file name carries its title.
- const shared = shown.filter((h) => h.note.scope !== "personal");
- recordActivity({
- repo: repoPlace(repo).key,
- kind: "search",
- asker: me,
- session: sessionKey(repo) ?? `${me}-${new Date().toISOString().slice(0, 10)}`,
- // A count, never the query or the paths: for the prompt hook the query is the person's prompt.
- file_count: files.length,
- shown_paths: shared.map((h) => noteName(h.note)),
- shown_authors: shared.map((h) => h.note.author),
- at: new Date().toISOString(),
- });
}
maybeSyncInBackground(repo);
}
@@@ -985,16 -964,11 +977,16 @@@ progra
program
.command("mcp", { hidden: TRAIL })
- .description("Serve the graph over MCP (stdio) — exposes graft_find_code, graft_trace_calls, graft_find_all, graft_file_api, graft_repo_map and graft_check_freshness as tools")
+ .description("Serve the graph over MCP (stdio): exposes graft_find_code, graft_trace_calls, graft_find_all, graft_file_api, graft_repo_map and graft_check_freshness as tools")
.argument(...DIR_ARG)
- .action(async (dirArg: string | undefined) => {
- const dir = noteQuery(queryRoot(dirArg));
+ .option("--brains", "serve only the connected Trail workspace's brain tools (what Claude Code gets after init --connect)")
+ .action(async (dirArg: string | undefined, opts: { brains?: boolean }) => {
const { startMcpServer } = await import("./mcp/server.js");
+ if (opts.brains) {
+ startMcpServer(process.cwd(), undefined, currentVersion, { brainsOnly: true });
+ return;
+ }
+ const dir = noteQuery(queryRoot(dirArg));
const globalOpts = program.opts<{ dir?: string }>();
startMcpServer(dir, globalOpts.dir, currentVersion);
});
@@@ -1332,22 -1168,26 +1186,38 @@@ grouped(program.command("init"), GROUP.
.option("-y, --yes", "skip the picker and wire every detected agent (the pre-0.8 default)")
.option("--no-global", "skip writes outside this repo (the ~/.codex/ config + hooks)")
.option("--verbose", "print every file written, the graph build's own output and the closing banner")
+ .option(
+ "--connect <code>",
+ "connect this machine to your Trail workspace with the one-time code from team.trailhq.com, and send it a summary of this repo (titles, counts and names; never code)",
+ )
+ .option("--pair <code>", "the pair code from Trail's onboarding page: that page shows this run live, then you review what it found")
+ .option("--server <url>", "the Trail that gave the code (default: Trail cloud, https://team.trailhq.com)")
+ .option("--plain", "look back without asking Claude to name what it finds")
+ .option("--look-back", "look back at your past sessions again, for what isn't kept or closed yet")
.action(async (dir: string, opts: InitOptions) => {
- await runInitCommand(dir, opts);
+ if (opts.connect !== undefined && opts.pair !== undefined) {
+ console.error("✗ --connect and --pair are two ways in: use the one your Trail page gave you");
+ process.exitCode = 1;
+ return;
+ }
+ if (opts.connect !== undefined) await runConnectInit(dir, opts);
+ else await runInitCommand(dir, opts);
});
+ // `trail init` prints this when there was no terminal to ask on (an agent ran
+ // it) or with --yes: the person picks what to keep from what the look-back
+ // found. An agent may run it only after the person answered (pre-bash checks).
+ program
+ .command("keep", { hidden: true })
+ .description("keep learnings `trail init` found: trail keep 1 3, or trail keep none")
+ .argument("<numbers...>", "the numbers from the list init printed, or none")
+ .action((numbers: string[]) => {
+ // The CLI half of the keep check (src/init/keep.ts): it needs the receipt the PreToolUse half wrote.
+ const r = keepCommand(numbers, process.env);
+ for (const line of r.lines) console.error(line);
+ if (r.code) process.exitCode = r.code;
+ });
+
/** Everything on stdin, or "" when nothing is piped in. */
async function readStdin(): Promise<string> {
if (process.stdin.isTTY) return "";
@@@ -1523,48 -1365,7 +1395,46 @@@ function printLines(lines: string[]): v
}
/** `graft init`'s flags, as commander hands them over. */
- interface InitOptions { build?: boolean; agents?: string[]; allAgents?: boolean; listAgents?: boolean; mcp?: boolean; hooks?: boolean; statusline?: boolean; dryRun?: boolean; yes?: boolean; global?: boolean; verbose?: boolean; connect?: string; pair?: string; server?: string }
-interface InitOptions { build?: boolean; agents?: string[]; allAgents?: boolean; listAgents?: boolean; mcp?: boolean; hooks?: boolean; statusline?: boolean; dryRun?: boolean; yes?: boolean; global?: boolean; verbose?: boolean; plain?: boolean; lookBack?: boolean }
++interface InitOptions { build?: boolean; agents?: string[]; allAgents?: boolean; listAgents?: boolean; mcp?: boolean; hooks?: boolean; statusline?: boolean; dryRun?: boolean; yes?: boolean; global?: boolean; verbose?: boolean; connect?: string; pair?: string; server?: string; plain?: boolean; lookBack?: boolean }
+
+/** What `init --connect` and `--pair` hear from a run of init, as it happens: the stages the web page ticks off. */
+interface InitProgress {
+ mapped?(m: { nodes: number; edges: number; files: number }): void;
+ /** What init learned this run (team and personal), and how many past sessions it read; `notes` is empty when it learned nothing new. */
+ learned?(l: { notes: Array<{ note: Note; sessions?: number }>; sessions: number }): void;
+}
+
+/**
+ * `--server <url>` on `init --connect` and `--pair`: the Trail that gave the
- * code, kept for the rest of this run as TRAIL_URL. False, after saying why,
- * when it isn't a URL.
++ * code, for the rest of this run (`useServer`, never the environment). False,
++ * after saying why, when it isn't a URL.
+ */
+function useServerOption(raw: string | undefined): boolean {
- const server = raw?.trim().replace(/\/+$/, "");
- if (!server) return true;
- if (!/^https?:\/\//.test(server)) {
++ if (raw === undefined || !raw.trim()) return true;
++ const server = serverUrl(raw);
++ if (!server) {
+ console.error("✗ --server takes a URL, like https://dev.trailhq.com");
+ process.exitCode = 1;
+ return false;
+ }
- process.env.TRAIL_URL = server;
++ useServer(server);
+ return true;
+}
+
+/**
+ * What `init --pair` hears from init, as the onboarding page's steps: the map
+ * is done when `mapped` fires, the past sessions when `learned` does. Nothing
+ * to say for a run that read no sessions (that step is already marked).
+ */
+function pairProgress(pair: PairRun): InitProgress {
+ return {
+ mapped: (m) => pair.phase("files", "done", m.files ? `${m.files.toLocaleString("en-US")} files` : "", m.files ? `Mapped ${m.files.toLocaleString("en-US")} files` : "Mapped the code"),
+ learned: (l) => {
+ if (l.sessions <= 0) return;
- // The PR reviews' learnings come with `sessions: 0`; the rest were said in past sessions.
- const fromSessions = l.notes.filter((n) => n.sessions !== 0).length;
- pair.phase("decisions", "done", `${l.sessions} sessions`, `Read ${l.sessions} past sessions: ${fromSessions} thing${fromSessions === 1 ? "" : "s"} you told Claude more than once`);
++ pair.phase("decisions", "done", `${l.sessions} sessions`, `Read ${l.sessions} past Claude sessions`);
+ },
+ };
+}
/** Repo-relative with forward slashes, for printing. */
function shown(repo: string, path: string): string {
@@@ -1703,23 -1481,15 +1575,21 @@@ async function runInitCommand(dir: stri
if (place.git) maybeRefreshBranches(place.checkout);
}
- // Under trail, with Claude Code picked: what the person kept telling Claude
- // in this repo's past sessions, and what reviewers kept flagging on its
- // merged PRs, read while the rest of init runs and saved as learnings at
- // the end. Once per repo, and never asked about first.
- const pastRead = TRAIL && wantClaude ? beginPastRead(repo) : null;
- if (pastRead) console.error(`· reading your ${pastRead.sessions} past Claude sessions here for what you keep telling Claude`);
- const reviewRead = TRAIL && wantClaude ? beginReviewRead(repo) : null;
- if (reviewRead) console.error("· reading review comments on this repo's merged PRs for what reviewers keep flagging");
+ // Under trail, with Claude Code picked: look back at this repo's past
+ // sessions and PR reviews while the rest of init runs, and offer what came
+ // up at the end. Nothing is kept without a tick (see src/init/review.ts).
+ const tty = Boolean(process.stdin.isTTY && process.stderr.isTTY);
+ const lookBack = TRAIL && wantClaude ? beginLookBack(repo, { plain: opts.plain === true, again: opts.lookBack === true }) : null;
+ for (const line of lookBack?.lines ?? []) console.error(line);
+ if (pair) {
- if (pastRead) pair.phase("decisions", "running", "", `Reading ${pastRead.sessions} past Claude sessions`);
++ if (lookBack?.reads.lb) pair.phase("decisions", "running", "", "Reading past Claude sessions");
+ else pair.phase("decisions", "done", "none here");
- if (reviewRead) pair.phase("prs", "running", "", "Reading review comments on merged PRs");
++ if (lookBack?.reads.reviews) pair.phase("prs", "running", "", "Reading review comments on merged PRs");
+ else pair.phase("prs", "done", "none here");
+ }
if (children.length)
- console.error(`· workspace: wiring ${repo} and ${children.length} child repo(s) — ${children.join(", ")}`);
+ console.error(`· workspace: wiring ${repo} and ${children.length} child repo(s): ${children.join(", ")}`);
// Today's output, file by file, behind --verbose. Everything else gets one
// line per step: the graph, then one per agent.
@@@ -1750,31 -1519,13 +1620,34 @@@
} else if (hasGraftIndex(repo)) {
graphLine = "✓ graph ready";
} else {
- graphLine = `· skipped the graph build — run ${cmd("graft build")}`;
+ graphLine = `· skipped the graph build: run ${cmd("graft build")}`;
}
}
+ // After the graph build too: it adds the map's ignore lines (`.trail/.gitignore` under trail, `.gitignore` and `.ignore`
+ // under graft), and those are init's writes.
+ recordInit(installSnaps);
+ // --pair hears the same stages --connect does; only the ones InitProgress
+ // has no slot for (a read starting, the PR read, nothing to read) stay inline.
+ const report: InitProgress | undefined = pair ? pairProgress(pair) : progress;
+ if (report?.mapped) {
+ const g = loadGraphCached(contextDirFor(repo, children.length ? undefined : program.opts<GlobalOpts>().dir));
+ report.mapped({
+ nodes: g?.meta.nodeCount ?? 0,
+ edges: g?.meta.edgeCount ?? 0,
+ files: g ? g.nodes.filter((n) => n.kind === "file").length : 0,
+ });
+ }
+
+ // With --pair, one lookup measured against reading the files whole: the
+ // page's token step. It needs the map, so it follows the build.
+ let tokens: ReturnType<typeof tokensOnOneLookup> = null;
+ if (pair) {
+ pair.phase("tokens", "running", "", "Measuring one lookup against reading the files");
+ tokens = tokensOnOneLookup(repo, { contextDir: program.opts<GlobalOpts>().dir });
+ pair.tokensDone(tokens);
+ }
+
if (!verbose) {
// Warnings and removals in full, whatever else is folded.
const removed = [...new Set(reports.flatMap((r) => r.retracted))];
@@@ -1790,113 -1541,34 +1663,49 @@@
}
}
- // 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.
+ // Under trail: what the look-back found, and #662's team rows (what
+ // reviewers kept flagging on merged PRs, and Claude Code's notes about the
+ // repo on this machine), what the person kept, where this repo's learnings
+ // are, and how many there already are.
let learnedNow = false;
- let skillsWritten: SavedSkill[] = [];
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 ? 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 && fromReviews.length + memory.length + fromSessions.length
- ? await pickLearnings([
- ...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.
- const keepFrom =
- <T>(from: number) =>
- picked === undefined
- ? 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 });
++ // What the look-back read, for the --pair and --connect pages.
++ let sessionsRead = 0;
+ if (lookBack) {
- const learned = await finishLookBack(repo, lookBack.reads, { yes: opts.yes === true, verbose: opts.verbose === true, say: (l) => console.error(l), ...(tty ? { io: { stdin: process.stdin, stdout: process.stderr } } : {}) });
++ // With --pair the person reviews what was found on Trail's page, so no screen here, as with no terminal.
++ const screen = tty && !pair;
++ const learned = await finishLookBack(repo, lookBack.reads, { yes: opts.yes === true, verbose: opts.verbose === true, say: (l) => console.error(l), ...(screen ? { io: { stdin: process.stdin, stdout: process.stderr } } : {}) });
+ // #662's lines for the team rows it kept with no screen, in its words.
+ const { fromReviews, fromMemory } = learned.teamKept ?? { fromReviews: null, fromMemory: null };
+ if (fromReviews?.saved.length) {
+ const n = fromReviews.saved.length;
+ const what = n < fromReviews.offered ? `kept ${n} of the ${fromReviews.offered} things` : `learned ${n} thing${n === 1 ? "" : "s"}`;
+ console.error(`✓ ${what} reviewers made authors change, from the last ${fromReviews.result.prs} merged PRs here`);
+ // saveReviewFindings keeps the findings' order.
+ fromReviews.saved.forEach((note, i) => console.error(` for your team · from review on ${(fromReviews.kept[i]?.prs ?? []).map((n) => `#${n}`).join(", ")}: ${note.title}`));
}
- 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 (fromMemory?.saved.length) {
+ console.error(`✓ kept ${fromMemory.saved.length} of the ${fromMemory.offered} notes your Claude keeps about this repo`);
+ for (const note of fromMemory.saved) console.error(` ${note.scope === "personal" ? "just for you " : "for your team"} · ${note.title}`);
}
- if (pastRead) {
- 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;
- const what = n < offered ? `kept ${n} of the ${offered} things` : `learned ${n} thing${n === 1 ? "" : "s"}`;
- console.error(`✓ ${what} you told Claude more than once, from your last ${result.read} sessions here, just for you`);
- // Each with how many sessions it was said in: saveFindings keeps the findings' order.
- saved.forEach((note, i) => {
- const said = kept[i]?.sessions.length ?? 0;
- const count = said > 1 ? `told Claude in ${said} sessions: ` : "";
- console.error(` just for you · ${count}${note.title}`);
- });
- } else if (cancelled) {
- console.error(`· saved none of the ${offered} things you told Claude more than once; ${cmd("graft init")} again asks again`);
- } else if (offered) {
- console.error(`· kept none of the ${offered} things you told Claude more than once`);
- } else if (result.reason === "failed") {
- console.error(`· couldn't read your past sessions this time; ${cmd("graft init")} again tries again`);
- }
- learned.push(...saved);
++ sessionsRead = learned.read?.sessions ?? 0;
++ const prs = learned.read?.prs;
++ if (pair && prs !== undefined && prs !== null) {
++ const n = fromReviews?.saved.length ?? 0;
++ pair.phase("prs", "done", `${prs} PRs`, `Read ${prs} merged PRs: ${n} thing${n === 1 ? "" : "s"} reviewers made authors change`);
+ }
- learnedNow = learned.length > 0;
- teamSaved = learned.filter((s) => s.scope === "repo").length;
- report?.learned?.({ notes: learnedFrom, sessions: sessionsRead });
++ // The team learnings kept with no screen, said in no past session; after a screen the page lists the repo's own.
++ const notes = [...(fromReviews?.saved ?? []), ...(fromMemory?.saved ?? [])].map((note) => ({ note, sessions: 0 }));
++ report?.learned?.({ notes, sessions: sessionsRead });
+ learnedNow = learned.kept > 0;
+ teamSaved = learned.team;
if (learnedNow) {
console.error("· Claude follows them from your next session");
- if (teamSaved) console.error(commitLines({}, teammatesOn(repo), "repo").uncommitted);
+ if (learned.inRepo) 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 || memory.length))) report?.learned?.({ notes: [], sessions: 0 });
++ // Not looked back (not trail, or not Claude Code): the page still gets its stage.
++ if (!lookBack) report?.learned?.({ notes: [], sessions: 0 });
if (TRAIL && !learnedNow) {
const home = notesHome.get(repo);
if (home) {
@@@ -1951,29 -1623,9 +1760,29 @@@
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.findings({ tokens, sessions: lookBack?.reads.lb ? sessionsRead : undefined, teammates });
++ await pair.finish(repo);
+ 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)"`,
);
@@@ -2266,19 -1831,17 +2081,17 @@@ grouped(program.command("uninstall"), G
*/
function loginCommand(name = "login"): Command {
return new Command(name)
- .description("Connect this machine to a Trail workspace: sign in, pick the repos it gets, invite your team")
- .argument("[dir]", "the repo you're in, ticked first in the picker", ".")
+ .description("Connect this machine to a Trail workspace: sign in, add this repo, invite your team")
+ .argument("[dir]", "the repo to add", ".")
- .option("--server <url>", "a self-hosted Trail, e.g. https://trail.acme.internal (default: Trail cloud)")
+ .option("--server <url>", "a self-hosted Trail, e.g. https://trail.acme.internal (default: Trail cloud, https://team.trailhq.com)")
.action(async (dir: string, opts: { server?: string }) => {
const repo = resolve(dir);
- const server = opts.server?.trim().replace(/\/+$/, "");
- if (server) {
- if (!/^https?:\/\//.test(server)) {
- console.error(`✗ --server takes a URL, like https://trail.acme.internal`);
- process.exitCode = 1;
- return;
- }
- process.env.TRAIL_URL = server;
+ // Saved on the link, so its sign-in and every upload after go there; nothing in the environment.
+ const server = opts.server === undefined ? undefined : serverUrl(opts.server);
+ if (server === null) {
+ console.error(`✗ --server takes a URL, like https://trail.acme.internal`);
+ process.exitCode = 1;
+ return;
}
const cloud = readCloud();
if (cloud) {
diff --cc src/cloud/lookup-activity.ts
index 1aa0dd74,00000000..972e3c12
mode 100644,000000..100644
--- a/src/cloud/lookup-activity.ts
+++ b/src/cloud/lookup-activity.ts
@@@ -1,57 -1,0 +1,57 @@@
+/**
+ * What a code lookup tells the workspace: the learnings it showed (a use) and
+ * the tokens the map saved against reading the files whole. Shared by the CLI's
+ * `ask` and the MCP `graft_find_code`, so both report the same event.
+ */
+import { askSavedTokens, type AskResult } from "../ask/ask.js";
+import { repoPlace } from "../notes/home.js";
+import { noteAuthor } from "../notes/git-facts.js";
+import { noteName } from "../notes/notes.js";
+import { sessionKey } from "./nudge.js";
+import { readCloud, type Cloud } from "./workspace.js";
+import { recordActivity, records } from "./workspace-sync.js";
+
+/** The file part of a hit's `file:Lx-Ly` pointer. */
+function pointerFile(pointer: string): string {
+ return pointer.replace(/:L\d+(-L?\d+)?$/, "");
+}
+
+/**
+ * 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. `savedTokens` is the
- * saving from a pack the caller already rendered (see formatAskWithSaved), so
- * the lookup isn't rendered a second time. Never throws.
++ * A count of the files, never the query or the paths: for the prompt hook the
++ * query is the person's prompt. Only learnings the workspace gets are named:
++ * a personal one's file name carries its title. `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(), 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 shown = (r.notes ?? []).filter((h) => h.note.scope !== "personal");
+ 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 query
- // and the files it touched are session text, and stay on this machine.
++ // A lookup that showed no learning leaves with its savings only.
+ const used = shown.length > 0;
+ recordActivity(
+ {
+ repo: key,
+ kind: "search",
+ asker: me,
+ session: sessionKey(repo) ?? `${me}-${new Date().toISOString().slice(0, 10)}`,
- query: used ? r.query : "",
- files: used ? [...new Set(r.hits.map((h) => pointerFile(h.pointer)))] : [],
++ file_count: used ? new Set(r.hits.map((h) => pointerFile(h.pointer))).size : 0,
+ shown_paths: shown.map((h) => noteName(h.note)),
+ shown_authors: shown.map((h) => h.note.author),
+ ...(saved > 0 ? { saved_tokens: saved } : {}),
+ at: new Date().toISOString(),
+ },
+ cloud,
+ );
+ } catch {
+ /* a lost event undercounts by one */
+ }
+}
diff --cc src/cloud/onboarding.ts
index 43bc9018,00000000..f9b4cb92
mode 100644,000000..100644
--- a/src/cloud/onboarding.ts
+++ b/src/cloud/onboarding.ts
@@@ -1,634 -1,0 +1,634 @@@
+/**
+ * `trail init --connect <CODE>`: the onboarding on team.trailhq.com.
+ *
+ * A person signs up on the web, picks "Writing Code", and is shown two
+ * commands: install trail, then `trail init --connect TRL-XXXX-XXXX`. The code
+ * is one-time and short-lived; claiming it gives this machine a workspace
+ * token, kept where `trail login` keeps one (`~/.trail/cloud.json`).
+ *
+ * While init runs, the page ticks off stages as this sends them: connected,
+ * mapped, learned, done. Before `done`, one summary of the repo goes up, for
+ * the "What Trail found" page:
+ *
+ * - tokens: one real lookup on the fresh code map, and what it saved
+ * - learnings: titles, a short line of each and how many sessions said it
+ * - teammates: other people's recently pushed branches that change the
+ * files this person works on, from git
+ *
+ * Summaries only (the onboarding's "route B"): never code, diffs or session
+ * text. Every call is bounded and never throws; offline, init carries on and
+ * says nothing about it.
+ */
+import { execFileSync } from "node:child_process";
+import { hostname } from "node:os";
+import { formatAsk, ask } from "../ask/ask.js";
+import { contextDirFor } from "../context/node-file.js";
+import { loadGraphCached } from "../graph/load.js";
+import { buildRepoMap } from "../graph/map.js";
+import { refreshBranches, safeRef } from "../notes/branches.js";
+import { cleanSubject } from "../notes/edit-overlap.js";
+import { changedFiles, ownPath } from "../notes/git-facts.js";
+import { repoName, repoPlace } from "../notes/home.js";
+import { listNotes, sectionLead, type Note } from "../notes/notes.js";
+import { DEFAULT_TRAIL_URL, isError, trailUrl, type ApiError, type Cloud } from "./workspace.js";
+
+type Fetch = typeof fetch;
+
+/* -------------------------------------------------------------------------- */
+/* the code */
+/* -------------------------------------------------------------------------- */
+
+/**
+ * The code as the page shows it, `TRL-7F2A-K9QD`, from however it was pasted:
+ * any case, with or without the prefix and dashes. Null when it can't be one.
+ */
+export function normalizeCode(raw: string): string | null {
+ const s = raw.trim().toUpperCase().replace(/[\s_]+/g, "-");
+ const bare = s.replace(/^TRL-?/, "").replace(/-/g, "");
+ if (!/^[A-Z0-9]{8}$/.test(bare)) return null;
+ return `TRL-${bare.slice(0, 4)}-${bare.slice(4)}`;
+}
+
+/**
+ * The repo as the workspace names it: `{name, remote_url}`, from which Trail
+ * derives its key. No path on this machine, and never a credential from the
+ * remote: the URL is rebuilt from the repo's key (`github.com/acme/retry` →
+ * `https://github.com/acme/retry`), so a token in an https remote stays here.
+ * A repo with no remote sends its name alone.
+ */
+export interface RepoRef {
+ name: string;
+ remote_url?: string;
+}
+
+export function repoRef(repo: string): RepoRef {
+ const place = repoPlace(repo);
+ if (place.key.startsWith("local/")) return { name: repoName(place.key, place.checkout) };
+ // The name as the remote spells it (`go-retryablehttp`, `Graft`); the key is lower-cased.
+ const origin = git(place.checkout, ["remote", "get-url", "origin"], 5000)?.trim() ?? "";
+ const last = origin.replace(/\.git\/?$/i, "").split(/[/:]/).pop() ?? "";
+ const name = /^[A-Za-z0-9._-]+$/.test(last) ? last : place.key.split("/").pop()!;
+ return { name, remote_url: `https://${place.key}` };
+}
+
+/** What the page shows for the terminal: `Rushabh's MacBook Pro` on a Mac, else the host name. */
+export function machineName(): string {
+ if (process.platform === "darwin") {
+ try {
+ const name = execFileSync("scutil", ["--get", "ComputerName"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2000 }).trim();
+ if (name) return name.slice(0, 80);
+ } catch {
+ /* the host name below */
+ }
+ }
+ try {
+ return hostname().replace(/\.(local|lan|home)$/i, "").slice(0, 80);
+ } catch {
+ return "";
+ }
+}
+
+export type ConnectResult =
+ | { cloud: Cloud }
+ /** The code is wrong, used or expired: say so, and connect nothing. */
+ | { error: string; reason: "invalid" }
+ /** Trail didn't answer: set up locally and say how to connect later. */
+ | { error: string; reason: "offline" };
+
+interface ConnectBody {
+ token?: string;
+ workspace?: { id?: string; name?: string; slug?: string; url?: string; invite_url?: string };
+ user?: { id?: string; name?: string; email?: string };
+}
+
+async function post<T>(
+ url: string,
+ body: unknown,
+ opts: { token?: string; timeoutMs?: number; fetchImpl?: Fetch },
+): Promise<{ status: number; body: T } | ApiError> {
+ const f = opts.fetchImpl ?? fetch;
+ try {
+ const headers: Record<string, string> = { "content-type": "application/json", accept: "application/json" };
+ if (opts.token) headers.authorization = `Bearer ${opts.token}`;
+ const res = await f(url, { method: "POST", headers, body: JSON.stringify(body), signal: AbortSignal.timeout(opts.timeoutMs ?? 10_000) });
+ const text = await res.text();
+ let json: unknown = null;
+ try {
+ json = text ? JSON.parse(text) : null;
+ } catch {
+ /* not JSON */
+ }
+ if (!res.ok) {
+ const msg = (json as { error?: unknown } | null)?.error;
+ return { error: typeof msg === "string" ? msg : `Trail answered ${res.status}`, status: res.status };
+ }
+ return { status: res.status, body: json as T };
+ } catch (err) {
+ const timedOut = err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError");
+ return { error: timedOut ? "Trail didn't answer in time" : "couldn't reach Trail" };
+ }
+}
+
+/**
+ * Claim the one-time code: `POST /api/public/cli/connect`. Gives back the
+ * connection to save, with no repos picked: the full learnings sync stays off
+ * for a machine connected this way, so only the summary below goes up.
+ */
+export async function claimConnectCode(
+ base: string,
+ code: string,
+ req: { machine: string; repo: RepoRef },
+ opts: { fetchImpl?: Fetch; now?: number } = {},
+): Promise<ConnectResult> {
+ const r = await post<ConnectBody>(`${base}/api/public/cli/connect`, { code, machine: req.machine, repo: req.repo }, { fetchImpl: opts.fetchImpl, timeoutMs: 15_000 });
+ if (isError(r)) {
+ if (r.status === undefined) return { error: r.error, reason: "offline" };
+ if (r.status >= 500) return { error: `Trail answered ${r.status}`, reason: "offline" };
+ if (r.status === 403) return { error: "the account that made this code is no longer in that workspace", reason: "invalid" };
+ if (r.status === 429) return { error: "too many tries just now; wait a minute and run it again", reason: "invalid" };
+ return { error: "that code was already used, has expired, or isn't right", reason: "invalid" };
+ }
+ const b = r.body;
+ const ws = b?.workspace;
+ if (!b?.token || !ws?.name) return { error: "Trail sent an answer with no workspace in it", reason: "offline" };
+ const id = ws.id ?? ws.slug ?? ws.name;
+ return {
+ cloud: {
+ url: base,
+ token: b.token,
+ user: { name: b.user?.name ?? "", email: b.user?.email ?? "" },
+ workspace: {
+ id,
+ name: ws.name,
+ // readCloud needs a slug to count the connection; the connect answer may not carry one.
+ slug: ws.slug || id,
+ url: ws.url || `${base}/`,
+ invite_url: ws.invite_url || `${base}/`,
+ },
+ repos: [],
+ linkedAt: opts.now ?? Date.now(),
+ via: "connect",
+ },
+ };
+}
+
+/**
+ * The command that connects later: `trail init --connect TRL-… --server <url>`,
+ * naming the Trail it was run against unless that's Trail cloud, so it
+ * reaches the same backend the code came from.
+ */
+export function connectAgain(command: string, code: string, base: string): string {
+ return `${command} --connect ${code}${base.replace(/\/+$/, "") === DEFAULT_TRAIL_URL ? "" : ` --server ${base}`}`;
+}
+
+/**
+ * What to say, once, when Trail didn't take the code because it couldn't be
+ * reached: which Trail, what happened, and the exact command to connect later.
+ * `· couldn't reach Trail at http://localhost:5173 · set this repo up anyway ·
+ * to connect it later: trail init --connect TRL-7F2A-K9QD --server http://localhost:5173`
+ */
+export function offlineLine(error: string, base: string, code: string, command: string): string {
+ const what = error.startsWith("Trail ") ? `Trail at ${base}${error.slice("Trail".length)}` : `couldn't reach Trail at ${base}`;
+ return `· ${what} · set this repo up anyway · to connect it later: ${connectAgain(command, code, base)}`;
+}
+
+/* -------------------------------------------------------------------------- */
+/* the stages and the summary */
+/* -------------------------------------------------------------------------- */
+
+export type Stage = "connected" | "mapped" | "learned" | "done";
+
+export interface TokensSummary {
+ /** What was asked, in words the page can show: `how Do works`. */
+ question: string;
+ /** The symbol asked about. */
+ symbol: string;
+ /** Tokens saved, the pack, and reading the files whole: the `tokens saved ≈` line's numbers. */
+ saved: number;
+ pack: number;
+ baseline: number;
+ pct: number;
+ /** How many files the baseline reads whole. */
+ files: number;
+}
+
+export interface LearningSummary {
+ title: string;
+ /** One line of it, no code blocks, at most 200 characters. */
+ body: string;
+ /** Past sessions it was said in; 0 when it didn't come from sessions. */
+ sessions: number;
+}
+
+export interface TeammateSummary {
+ name: string;
+ email: string;
+ /** `kumar/retry`, without `origin/`. */
+ branch: string;
+ /** The files it changes that this person works on too (or, with no history of theirs, the repo's busiest). */
+ files: string[];
+ /** One line, from the branch's commit subjects. */
+ change: string;
+ /** When its newest commit was made, ISO. */
+ pushed_at: string;
+ /** Commits on the branch since it left the default branch. */
+ commits?: number;
+ /** When it changes a file one of this repo's learnings is about: which, and which learning. */
+ conflict?: string;
+}
+
+export interface RepoSummary {
+ repo: RepoRef;
+ tokens: TokensSummary | null;
+ /** Past sessions init read for learnings; absent when it read none this time. */
+ sessions?: number;
+ learnings: LearningSummary[];
+ teammates: TeammateSummary[];
+}
+
+/**
+ * Sends the stages and the summary for one `init --connect`, in order. The
+ * first call that can't reach Trail turns the rest off, so a laptop offline
+ * waits on one timeout at most. Never throws.
+ */
+export class OnboardingReporter {
+ private offline = false;
+ private chain: Promise<unknown> = Promise.resolve();
+ readonly sent: Array<{ path: string; body: unknown; ok: boolean }> = [];
+
+ constructor(
+ private readonly cloud: Cloud,
+ readonly repo: RepoRef,
+ private readonly opts: { fetchImpl?: Fetch; timeoutMs?: number; machine?: string } = {},
+ ) {}
+
+ private send(path: string, body: unknown): Promise<boolean> {
+ const next = this.chain.then(async () => {
+ if (this.offline) return false;
+ const r = await post(`${this.cloud.url}${path}`, body, { token: this.cloud.token, fetchImpl: this.opts.fetchImpl, timeoutMs: this.opts.timeoutMs ?? 5_000 });
+ const ok = !isError(r);
+ // No answer at all: offline, or Trail is down. An HTTP error is this call's alone.
+ if (isError(r) && r.status === undefined) this.offline = true;
+ this.sent.push({ path, body, ok });
+ return ok;
+ });
+ this.chain = next.catch(() => false);
+ return next.catch(() => false);
+ }
+
+ /** One stage, for the page to tick off. */
+ stage(stage: Stage, data: Record<string, unknown> = {}): Promise<boolean> {
+ return this.send("/api/cli/onboarding/events", { repo: this.repo, stage, machine: this.opts.machine, data });
+ }
+
+ summary(s: Omit<RepoSummary, "repo">): Promise<boolean> {
+ return this.send("/api/cli/repos/summary", { repo: this.repo, ...s });
+ }
+
+ /** Wait for everything sent so far. */
+ async flush(): Promise<void> {
+ await this.chain;
+ }
+}
+
+/* tokens ------------------------------------------------------------------- */
+
+/** The numbers in `ask`'s `[trail] tokens saved ≈ N (P%) — this pack ≈ … tok vs reading the F source file(s) whole ≈ B tok` line. */
+export function parseAskSavings(text: string): Omit<TokensSummary, "question" | "symbol"> | null {
+ const m = text.match(/\[(?:graft|trail)\] tokens saved ≈ ([\d,]+) \((\d+)%\) — this pack ≈ ([\d,]+) tok vs reading the (\d+) source file\(s\) whole ≈ ([\d,]+) tok/);
+ if (!m) return null;
+ const n = (s: string) => Number(s.replace(/,/g, ""));
+ return { saved: n(m[1]!), pct: n(m[2]!), pack: n(m[3]!), files: n(m[4]!), baseline: n(m[5]!) };
+}
+
+/** Folders that hold tests, fixtures, vendored or generated code, anywhere in a path. */
+const NOT_PRODUCT_DIR = /(^|\/)(test|tests|__tests__|testdata|test-fixtures|fixtures|__fixtures__|__mocks__|vendor|third_party|node_modules|generated|__generated__|gen)\//i;
+/** File names of tests and generated code: `client_test.go`, `a.test.ts`, `a.spec.js`, `test_client.py`, `api.pb.go`, `schema.generated.ts`. */
+const NOT_PRODUCT_FILE = /(_test\.[^/]+|\.(test|spec)\.[^/]+|_spec\.[^/]+|(^|\/)test_[^/]+\.py|(^|\/)conftest\.py|\.(generated|gen)\.[^/]+|\.pb\.go|_pb2(_grpc)?\.py|\.d\.ts)$/i;
+
+/** Whether a repo path is test, fixture, vendored or generated code, which a lookup shouldn't be measured on. */
+export function notProductCode(path: string): boolean {
+ const p = path.split("\\").join("/");
+ return NOT_PRODUCT_DIR.test(p) || NOT_PRODUCT_FILE.test(p);
+}
+
+/** Docs and config: prose, data and settings files, and the folders that hold them. */
+const DOC_OR_CONFIG_FILE = new RegExp(
+ [
+ "\\.(md|mdx|markdown|rst|adoc|txt|json|jsonc|ya?ml|toml|ini|cfg|conf|env|lock|xml|csv|svg|png|jpe?g|gif|ico)$",
+ "(^|/)(readme|changelog|changes|history|license|licence|notice|authors|contributors|codeowners|security)$",
+ "(^|/)(makefile|dockerfile|procfile|go\\.mod|go\\.sum)$",
+ // Dotfiles: .gitignore, .eslintrc.js, .env.local.
+ "(^|/)\\.[^/]+$",
+ ].join("|"),
+ "i",
+);
+const DOC_OR_CONFIG_DIR = /(^|\/)(docs?|\.github|\.circleci|\.vscode|\.idea)\//i;
+
+/** Whether a repo path is docs or config rather than code. */
+export function docOrConfig(path: string): boolean {
+ const p = path.split("\\").join("/");
+ return DOC_OR_CONFIG_DIR.test(p) || DOC_OR_CONFIG_FILE.test(p);
+}
+
+/**
+ * A teammate's files with the one worth naming first: product code (by the
+ * same rules as the tokens lookup), then other code (tests, fixtures,
+ * vendored, generated), then docs and config. Every file stays; only the
+ * order changes, and within each kind it's git's. The page says a teammate
+ * "is changing" the first one, which shouldn't be CHANGELOG.md when they
+ * also change client.go.
+ */
+export function headlineOrder(files: string[]): string[] {
+ const rank = (f: string) => (docOrConfig(f) ? 2 : notProductCode(f) ? 1 : 0);
+ return files.map((f, i) => ({ f, i, r: rank(f) })).sort((a, b) => a.r - b.r || a.i - b.i).map((x) => x.f);
+}
+
+const COMMON_UTIL_NAMES = new Set(["cn", "utils", "index", "helpers", "main", "init", "config", "setup", "test"]);
+
+/** Whether a symbol name is worth measuring a lookup on: at least 5 characters and not a common util name. */
+export function meaningfulSymbol(name: string): boolean {
+ return name.length >= 5 && !COMMON_UTIL_NAMES.has(name.toLowerCase());
+}
+
+/**
+ * One real lookup on the code map, as an agent would make it: a question
+ * about the repo's most central symbol (most incoming edges, with a name of
+ * 5+ characters that isn't a common util name) outside tests,
+ * fixtures, vendored and generated code, answered with
+ * the code inlined, and what that saved against reading the files it covers
+ * whole. The next most central is tried when a lookup saves nothing (tiny
+ * files). Null without a graph.
+ */
+export function tokensOnOneLookup(repo: string, opts: { contextDir?: string; tries?: number } = {}): TokensSummary | null {
+ try {
+ const graph = loadGraphCached(contextDirFor(repo, opts.contextDir));
+ if (!graph) return null;
+ // The most central symbols of the product code: tests, fixtures, vendored
+ // and generated code only when there's nothing else.
+ // A name worth asking about: a short or generic one (`cn`, `utils`, `main`)
+ // says nothing about the repo, so the example would be meaningless.
+ // Falls back to every symbol when no name passes, so a repo of short names still gets a figure.
+ const spots = buildRepoMap(graph, { hotspots: 500 }).hotspots;
+ const named = spots.filter((h) => meaningfulSymbol(h.name));
+ const all = named.length ? named : spots;
+ const product = all.filter((h) => !notProductCode(h.path));
+ const hubs = (product.length ? product : all).slice(0, Math.max(1, opts.tries ?? 5));
+ for (const hub of hubs) {
+ const query = `how does ${hub.name} work`;
+ const r = ask(repo, query, { source: true, limit: 5, contextDir: opts.contextDir });
+ const got = parseAskSavings(formatAsk(r));
+ if (got && got.saved > 0) return { question: `how ${hub.name} works`, symbol: hub.name, ...got };
+ }
+ return null;
+ } catch {
+ return null;
+ }
+}
+
+/* learnings ---------------------------------------------------------------- */
+
+/** How many sessions a learning read from past sessions was said in, from the line init writes under it. */
+export function sessionsIn(body: string): number {
+ const m = body.match(/Told to Claude in (\d+) past sessions/);
+ return m ? Number(m[1]) : 0;
+}
+
+/**
+ * One line of a learning, for a card: the first point under `## Decided` (or
+ * the first line of prose), no code blocks, headings or provenance line, at
+ * most 200 characters.
+ */
+export function shortBody(body: string): string {
+ const prose = body
+ .replace(/```[\s\S]*?(```|$)/g, " ")
+ .split(/\r?\n/)
+ .filter((l) => !/^_(Told to Claude|Flagged in review) /.test(l.trim()));
+ const text = prose.join("\n");
+ const lead =
+ sectionLead(text, "Decided") ??
+ sectionLead(text, "Watch out") ??
+ prose.map((l) => l.trim()).find((l) => l && !l.startsWith("#")) ??
+ "";
+ const one = lead.replace(/^[-*]\s+/, "").replace(/\s+/g, " ").trim();
+ return one.length > 200 ? `${one.slice(0, 199)}…` : one;
+}
+
+/**
+ * The team's learnings in this repo, for the summary: what init just learned
+ * when it learned something (with the sessions each was said in), else what
+ * `.trail/learnings/` already has. Never a personal one: those stay on this
+ * machine.
+ */
+export function learningsSummary(repo: string, learned: Array<{ note: Note; sessions?: number }> | null, max = 10): LearningSummary[] {
+ try {
+ const notes: Array<{ note: Note; sessions?: number }> = learned?.length
+ ? learned.filter((l) => l.note.scope !== "personal")
+ : listNotes(repo, { branches: false })
+ .filter((n) => n.scope === "repo" && !n.ref)
+ .map((note) => ({ note }));
+ return notes.slice(0, max).map(({ note, sessions }) => ({
+ title: note.title.slice(0, 200),
+ body: shortBody(note.body),
+ sessions: sessions ?? sessionsIn(note.body),
+ }));
+ } catch {
+ return [];
+ }
+}
+
+/* teammates ---------------------------------------------------------------- */
+
+function git(repo: string, args: string[], timeout = 15_000): string | null {
+ try {
+ return execFileSync("git", args, {
+ cwd: repo,
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ timeout,
+ maxBuffer: 16 * 1024 * 1024,
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
+ });
+ } catch {
+ return null;
+ }
+}
+
+const BOT = /\[bot\]|^(dependabot|github-actions|renovate)\b/i;
+
+/** Branches that are where work lands, not work in flight: nobody is "on" them. */
+const INTEGRATION_BRANCH = /^(main|master|dev|develop|staging|production|release\/.+)$/;
+
+/**
+ * Whether a remote branch is open work by someone: not the remote's default
+ * branch (`base`), not a shared integration branch, and not fully merged
+ * already (its tip is an ancestor of `base`).
+ */
+export function openBranch(repo: string, base: string, ref: string): boolean {
+ const name = ref.replace(/^origin\//, "");
+ if (ref === base || name === base.replace(/^origin\//, "") || INTEGRATION_BRANCH.test(name)) return false;
+ // `merge-base --is-ancestor` exits 0 when merged, 1 when not; git() returns null on a nonzero exit.
+ return git(repo, ["merge-base", "--is-ancestor", ref, base]) === null;
+}
+
+/** Files `email` changed in the last `days` days on any branch, plus what's uncommitted here. */
+export function myRecentFiles(repo: string, email: string, days = 30): string[] {
+ const out = new Set<string>(changedFiles(repo, undefined, 200));
+ if (email) {
+ const pattern = `<${email.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}>`;
+ const log = git(repo, ["log", "--all", "--no-merges", `--since=${days}.days`, `--author=${pattern}`, "--name-only", "--format="]);
+ for (const f of (log ?? "").split("\n")) if (f.trim() && !ownPath(f.trim())) out.add(f.trim());
+ }
+ return [...out].slice(0, 500);
+}
+
+/** The repo's busiest files lately: the stand-in for "files you work on" when you have no history here. */
+export function hottestFiles(repo: string, n = 30): string[] {
+ const count = new Map<string, number>();
+ const log = git(repo, ["log", "--no-merges", "--since=90.days", "-n", "2000", "--name-only", "--format="]) || git(repo, ["log", "--no-merges", "-n", "300", "--name-only", "--format="]);
+ for (const raw of (log ?? "").split("\n")) {
+ const f = raw.trim();
+ if (f && !ownPath(f)) count.set(f, (count.get(f) ?? 0) + 1);
+ }
+ return [...count].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, n).map(([f]) => f);
+}
+
+/** One line of what a branch does, from its commit subjects, newest first. */
+function changeLine(repo: string, base: string, ref: string): string {
+ const subjects = (git(repo, ["log", "--no-merges", "--format=%s", "-n", "5", `${base}..${ref}`]) ?? "")
+ .split("\n")
+ .map((s) => cleanSubject(s))
+ .filter(Boolean);
+ const line = [...new Set(subjects)].slice(0, 3).join("; ");
+ return line.length > 160 ? `${line.slice(0, 159)}…` : line;
+}
+
+/**
+ * `git fetch` in the foreground, at the end of init, without ever stopping to
+ * ask: no credential prompt, and no ssh passphrase prompt unless the person
+ * set up their own ssh command (then theirs is used as is).
+ */
+function fetchQuietly(repo: string): void {
+ try {
+ const env: NodeJS.ProcessEnv = { ...process.env, GIT_TERMINAL_PROMPT: "0" };
+ if (!env.GIT_SSH_COMMAND && !git(repo, ["config", "core.sshCommand"])?.trim()) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
+ execFileSync("git", ["fetch", "--quiet", "--prune", "origin"], { cwd: repo, stdio: "ignore", timeout: 20_000, env });
+ } catch {
+ /* offline, or no origin: the refs already here */
+ }
+}
+
+/**
+ * The names a learning is about, to look for in a teammate's change: the
+ * symbols its `touches` name (`client.go#Do`), and code-like words in its
+ * title and lead line (`defaultRetryMax`, `retry_max`, `Do()`). Plain words
+ * are left out: "retry" in a learning says nothing about a change.
+ */
+export function learningTerms(n: Note): string[] {
+ const terms = new Set<string>();
+ for (const t of n.touches) {
+ const sym = t.split("#")[1];
+ if (sym) terms.add(sym.split(".").pop()!);
+ }
+ const text = `${n.title} ${shortBody(n.body)}`;
+ // camelCase, PascalCase with an inner capital, snake_case, or a call: `Do()`.
+ for (const w of text.match(/\b[A-Za-z_][A-Za-z0-9_]*\b(\(\))?/g) ?? []) {
+ const word = w.replace(/\(\)$/, "");
+ if (w.endsWith("()") || /[a-z][A-Z]/.test(word) || /[A-Za-z]_[A-Za-z]/.test(word)) terms.add(word);
+ }
+ return [...terms].filter((t) => t.length >= 2);
+}
+
+/**
+ * When a teammate's branch changes a name one of the team's learnings is
+ * about, in a file that learning touches: `Changes defaultRetryMax in
+ * client.go, which your learning "Keep defaultRetryMax at 4" is about.` Read
+ * from the branch's diff here; only this line goes up. Nothing when the
+ * learning names nothing code-like, or the change doesn't touch it.
+ */
+export function conflictLine(repo: string, base: string, ref: string, files: string[], learnings: Note[]): string | undefined {
+ const changed = new Set(files);
+ for (const n of learnings) {
+ if (n.scope === "personal") continue;
+ const terms = learningTerms(n);
+ if (terms.length === 0) continue;
+ for (const file of n.touches.map((t) => t.split("#")[0]!).filter((f) => changed.has(f))) {
+ const diff = git(repo, ["diff", "--unified=0", `${base}...${ref}`, "--", file]) ?? "";
+ const lines = diff.split("\n").filter((l) => /^[+-]/.test(l) && !/^(\+\+\+|---) /.test(l));
+ const hit = terms.find((t) => lines.some((l) => new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`).test(l)));
+ if (hit) {
+ const line = `Changes ${hit} in ${file}, which your learning "${n.title.replace(/"/g, "'")}" is about.`;
+ return line.length > 300 ? `${line.slice(0, 299)}…` : line;
+ }
+ }
+ }
+ return undefined;
+}
+
+/**
+ * Teammates' work in the same place: remote branches whose newest commit is
+ * from the last `days` days and from someone other than this person, that
+ * change files this person changed lately (or the repo's busiest files, when
+ * they have no history here). Newest first. Fetches first unless
+ * `fetch: false` (or TRAIL_NO_FETCH). Names, emails, branch and file names and
+ * commit subjects only: never a diff.
+ */
+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;
+ const me = (git(repo, ["config", "user.email"]) ?? "").trim().toLowerCase();
+ 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 undefined;
+ const mine = new Set(myRecentFiles(repo, me));
+ const where = mine.size ? mine : new Set(hottestFiles(repo));
+ const out: TeammateSummary[] = [];
+ for (const b of cache.branches) {
+ if (now - b.at > days * 24 * 60 * 60 * 1000) continue;
+ if (!openBranch(repo, cache.base, b.ref)) continue;
+ const [name = "", email = ""] = (git(repo, ["log", "-1", "--format=%aN%x09%aE", b.ref]) ?? "").trim().split("\t");
+ if (!name || BOT.test(name)) continue;
+ if ((me && email.toLowerCase() === me) || (myName && name.toLowerCase() === myName)) continue;
+ const files = headlineOrder(b.files.filter((f) => !ownPath(f) && where.has(f)));
+ if (files.length === 0) continue;
+ const commits = Number((git(repo, ["rev-list", "--count", `${cache.base}..${b.ref}`]) ?? "").trim());
+ const conflict = conflictLine(repo, cache.base, b.ref, files, opts.learnings ?? []);
+ out.push({
+ name: name.slice(0, 80),
+ email: email.slice(0, 120),
+ branch: safeRef(b.ref.replace(/^origin\//, "")),
+ files: files.slice(0, 20),
+ change: changeLine(repo, cache.base, b.ref),
+ pushed_at: new Date(b.at).toISOString(),
+ ...(Number.isFinite(commits) && commits > 0 ? { commits } : {}),
+ ...(conflict ? { conflict } : {}),
+ });
+ if (out.length >= (opts.max ?? 10)) break;
+ }
+ return out.sort((a, b) => b.pushed_at.localeCompare(a.pushed_at));
+ } catch {
+ return undefined;
+ }
+}
+
- /** The Trail a code is claimed against: `--server`, TRAIL_URL, or Trail cloud. */
++/** The Trail a code is claimed against: `--server` for this run (useServer), or Trail cloud. */
+export function connectBase(env: NodeJS.ProcessEnv = process.env): string {
+ return trailUrl(env);
+}
diff --cc src/cloud/pair.ts
index 66d2479e,00000000..aeb8cf9a
mode 100644,000000..100644
--- a/src/cloud/pair.ts
+++ b/src/cloud/pair.ts
@@@ -1,296 -1,0 +1,294 @@@
+/**
+ * `trail init --pair CODE`: the setup prompt a person copied from Trail's
+ * onboarding page carries a pair code. With it, init tells Trail about itself
+ * before doing anything slow, so the page the person is on moves on to sign-up
+ * at once; then it streams what it's doing (the map, the PRs, past sessions,
+ * the learnings it wrote) to the page that shows it live, and hands over what
+ * it found for the person to review there.
+ *
+ * Nothing goes up as a workspace learning from here. The person keeps or drops
+ * each one on the review page, and Trail stores that. A detached
+ * `_trail-pair` child then waits for the connection, saves it, waits for the
+ * review, and uploads the repo the usual way, which leaves a dropped learning
+ * dropped.
+ */
+import { spawn } from "node:child_process";
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+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 { skillDirs, skillName } from "../skills/skills.js";
+import { matter } from "../util/front-matter.js";
- import { newState, pickerRepos } from "./nudge.js";
++import { newState } from "./nudge.js";
+import type { TeammateSummary, TokensSummary } from "./onboarding.js";
- import { dropActivity, learningsPayload, syncRepo } from "./workspace-sync.js";
++import { dropActivity, reviewPayload, syncRepo } from "./workspace-sync.js";
+import { claimHandoff, fetchMe, isError, postHandoffProgress, readCloud, registerHandoff, trailUrl, writeCloud, type Cloud } from "./workspace.js";
+
+/** A pair code as the onboarding page prints it: letters and digits. */
+export function validPairCode(code: string): boolean {
+ return /^[A-Za-z0-9-]{6,64}$/.test(code.trim());
+}
+
+export type PhaseId = "install" | "files" | "tokens" | "prs" | "decisions" | "team" | "learnings";
+type PhaseStatus = "todo" | "running" | "done";
+interface Phase {
+ id: PhaseId;
+ label: string;
+ status: PhaseStatus;
+ count: string;
+}
+
+/**
+ * What init found out beyond the learnings, for the onboarding page: one
+ * lookup's token saving, the sessions read, and teammates' branches on this
+ * person's files. An empty `teammates` list means "checked, none".
+ */
+export interface PairFindings {
+ tokens?: TokensSummary | null;
+ sessions?: number;
+ teammates?: TeammateSummary[];
+}
+
+/**
+ * One team skill init just wrote as a found item. Nothing for a skill that was
+ * already there, a skill kept for the person alone, or a file that isn't under
+ * the repo's own `.claude/skills/`: only what init wrote into the repo goes up.
+ */
+function foundSkillItem(checkout: string, s: SavedSkill): Record<string, unknown>[] {
+ const name = skillName(s.skill.name);
+ const expected = join(skillDirs(checkout).repo, name, "SKILL.md");
+ if (!s.created || s.skill.for !== "team" || !name || resolve(s.path) !== resolve(expected)) return [];
+ let text: string;
+ try {
+ text = readFileSync(s.path, "utf8");
+ } catch {
+ return [];
+ }
+ return [
+ {
+ kind: "skill",
+ path: `.claude/skills/${name}/SKILL.md`,
+ title: s.skill.title,
+ author: noteAuthor(checkout),
+ body: matter(text).content.trim(),
+ hash: createHash("sha256").update(text).digest("hex"),
+ touches: [],
+ },
+ ];
+}
+
+/** "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;
+/** The most found items Trail keeps from one read. */
+const MAX_FOUND = 500;
+
+/**
+ * One init run, reported to the onboarding page. Every call is best effort:
+ * a slow or unreachable Trail never holds up or fails init.
+ */
+export class PairRun {
+ readonly state: string;
+ readonly url: string;
+ private readonly base: string;
+ private phases: Phase[];
+ private chain: Promise<unknown> = Promise.resolve();
+ private readonly fetchImpl?: typeof fetch;
+
+ private constructor(base: string, state: string, url: string, version: string, fetchImpl?: typeof fetch) {
+ this.base = base;
+ this.fetchImpl = fetchImpl;
+ this.state = state;
+ this.url = url;
+ this.phases = [
+ { id: "install", label: "Install Trail-code", status: "done", count: version },
+ { id: "files", label: "Map the code", status: "todo", count: "" },
+ { id: "tokens", label: "Measure one lookup", status: "todo", count: "" },
+ { id: "prs", label: "Read pull request reviews", status: "todo", count: "" },
+ { id: "decisions", label: "Read past Claude sessions", status: "todo", count: "" },
+ { id: "team", label: "Check your team's branches", status: "todo", count: "" },
+ { id: "learnings", label: "Write learnings", status: "todo", count: "" },
+ ];
+ }
+
+ /**
+ * Tell Trail about this run, with the pair code, and return it; null when
+ * Trail can't be reached or turns the code down (init carries on without it).
+ */
+ static async start(repo: string, code: string, opts: { agent: string; version: string; fetchImpl?: typeof fetch }): Promise<PairRun | { error: string }> {
+ const base = trailUrl();
+ const state = newState();
+ const place = repoPlace(repo);
+ const current = place.git ? { key: place.key, name: repoName(place.key, place.checkout) } : null;
- // This repo first, with the learnings it already has: init hasn't told
- // Trail about it yet, so the list of known repos may not have it.
- const here = place.git ? learningsPayload(place.checkout).filter((l) => l.ref === "" && l.kind !== "skill").length : 0;
- const known = pickerRepos().filter((r) => r.key !== current?.key);
- if (current) known.unshift({ ...current, learnings: here });
++ // This repo only, with the learnings it already has: nobody has signed in
++ // yet, so nothing tells Trail what else is on this machine.
++ const here = place.git ? reviewPayload(place.checkout).filter((l) => l.ref === "" && l.kind !== "skill").length : 0;
++ const known = current ? [{ ...current, learnings: here }] : [];
+ const reg = await registerHandoff(
+ base,
+ { state, repo: current, repos: known, author: noteAuthor(repo), pair: code.trim().toUpperCase() },
+ opts.fetchImpl,
+ );
+ if (isError(reg)) return { error: reg.error };
+ const run = new PairRun(base, state, reg.url, opts.version, opts.fetchImpl);
+ run.send({ agent: opts.agent, phases: run.phases, log: [`Installed Trail-code ${opts.version}`] });
+ return run;
+ }
+
+ /** Move a step on: running, or done with what it counted. */
+ phase(id: PhaseId, status: PhaseStatus, count = "", log?: string): void {
+ this.phases = this.phases.map((p) => (p.id === id ? { ...p, status, count: count || p.count } : p));
+ 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> = {};
+ if (f.tokens) out.tokens = f.tokens;
+ if (f.sessions !== undefined) out.sessions = f.sessions;
+ if (f.teammates !== undefined) out.teammates = f.teammates;
+ this.send({ findings: out });
+ }
+
+ /**
+ * Hand over the repo's learnings and skills, 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, so it stays off the page.
+ */
+ finish(repo: string, skills: SavedSkill[] = []): Promise<void> {
+ const place = repoPlace(repo);
+ // Everything the person's agents now start from in this repo, so the page
+ // counts what the home will: their learnings and teammates' pushed ones,
+ // then the skills this run wrote and the ones the repo already has.
+ const found: Record<string, unknown>[] = [];
+ if (place.git) {
- const payload = learningsPayload(place.checkout);
++ const payload = reviewPayload(place.checkout);
+ const item = (l: (typeof payload)[number]) => ({
+ kind: l.kind === "skill" ? "skill" : "decision", path: l.path, title: l.title, author: l.author, body: l.body, hash: l.hash, touches: l.touches,
+ });
+ const written = skills.flatMap((s) => foundSkillItem(place.checkout, s));
+ const paths = new Set(written.map((w) => w.path));
+ found.push(
+ ...payload.filter((l) => l.kind !== "skill").map(item),
+ ...written,
+ ...payload.filter((l) => l.kind === "skill" && !paths.has(l.path)).map(item),
+ );
+ found.splice(MAX_FOUND); // Trail takes this many from one read
+ }
+ 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: [foundLine(learned, m)] } : {}) });
+ }
+ this.send({ done: true });
+ return this.flush();
+ }
+
+ /** Wait for every report so far to be sent (or to fail). */
+ flush(): Promise<void> {
+ return this.chain.then(() => undefined);
+ }
+
- /** Start the detached wait for the connection and the review. */
++ /** Start the detached wait for the connection and the review, at the Trail this run reported to. */
+ handOff(repo: string): void {
- const child = spawn(process.execPath, [graftCliPath(), "_trail-pair", this.state, repo], {
++ const child = spawn(process.execPath, [graftCliPath(), "_trail-pair", this.state, repo, this.base], {
+ detached: true,
+ stdio: "ignore",
+ windowsHide: true,
- env: { ...process.env, TRAIL_URL: this.base },
+ });
+ child.unref();
+ }
+
+ private send(body: Record<string, unknown>): void {
+ // One after another, so the page sees the steps in order.
+ this.chain = this.chain.then(() => postHandoffProgress(this.base, { state: this.state, ...body }, this.fetchImpl)).catch(() => undefined);
+ }
+}
+
+export interface FinishOptions {
+ fetchImpl?: typeof fetch;
+ sleep?: (ms: number) => Promise<void>;
+ now?: () => number;
+ /** How long to wait for the person, all told. */
+ waitMs?: number;
+}
+
+/** Wait an hour at most for someone to sign up, connect and review. */
+const FINISH_WAIT_MS = 60 * 60 * 1000;
+
+/**
+ * What `_trail-pair` runs: wait for the person to connect in the browser, save
+ * the connection, wait for their review, then upload this repo's learnings.
+ * Returns what happened, for tests.
+ */
+export async function finishPair(state: string, repo: string, opts: FinishOptions = {}): Promise<"uploaded" | "expired" | "timed_out" | "failed"> {
+ const now = opts.now ?? Date.now;
+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
+ const started = now();
+ const late = () => now() - started >= (opts.waitMs ?? FINISH_WAIT_MS);
+ const base = trailUrl();
+
+ let cloud: Cloud | null = null;
+ for (;;) {
+ const got = await claimHandoff(base, state, opts.fetchImpl);
+ if ("cloud" in got) {
+ cloud = { ...got.cloud, url: base, linkedAt: now() };
+ // Like any first connect: nothing recorded before it goes up.
+ dropActivity();
+ writeCloud(cloud);
+ break;
+ }
+ if ("error" in got) return "expired";
+ if (late()) return "timed_out";
+ await sleep(1500);
+ }
+
+ // Trail turns progress away once the review is in: that's the signal.
+ for (;;) {
+ const r = await postHandoffProgress(base, { state }, opts.fetchImpl);
+ if (r === "reviewed") break;
+ if (r === "gone") return "expired";
+ if (late()) return "timed_out";
+ await sleep(2000);
+ }
+
+ // The review added this repo to the workspace; pick that up, then upload.
+ const me = await fetchMe(cloud, opts.fetchImpl);
+ if (!isError(me)) {
+ cloud = { ...cloud, user: me.user, workspace: me.workspace, repos: me.repos.map((r) => r.key) };
+ writeCloud(cloud);
+ }
+ const place = repoPlace(repo);
+ if (!place.git) return "uploaded";
+ const res = await syncRepo(place.checkout, readCloud() ?? cloud, { fetch: false, fetchImpl: opts.fetchImpl });
+ return isError(res) ? "failed" : "uploaded";
+}
diff --cc src/cloud/workspace-sync.ts
index c2ad111e,9c76e18a..36d26d57
--- a/src/cloud/workspace-sync.ts
+++ b/src/cloud/workspace-sync.ts
@@@ -18,17 -22,19 +22,21 @@@
* `_trail-sync` child does it.
*/
import { createHash } from "node:crypto";
-import { spawn } from "node:child_process";
-import { existsSync, readFileSync, renameSync, rmSync, statSync } from "node:fs";
-import { basename, join } from "node:path";
+import { execFileSync, spawn } from "node:child_process";
- import { appendFileSync, existsSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
++import { existsSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync } from "node:fs";
+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";
-import { LEARNINGS_DIR } from "../notes/repo-trail.js";
+import { LEARNINGS_DIR, learningFiles, readLearningFile } from "../notes/repo-trail.js";
- import { parseNote } from "../notes/notes.js";
+ import { parseNote, type Note } from "../notes/notes.js";
+ import { liveLearnings } from "../notes/learning-fields.js";
+ import { secretReason } from "../notes/secrets.js";
+import { OWN_SKILLS, skillDirs } from "../skills/skills.js";
+import { matter } from "../util/front-matter.js";
+ import { appendPrivateFile, ensurePrivateDir, PRIVATE_FILE_MODE, writePrivateFile } from "../util/private-file.js";
import { cacheDir, readJson, writeJsonAtomic } from "../util/state.js";
+ import { headLearnings } from "./head-learnings.js";
import { isError, postActivity, readCloud, uploadLearnings, type ActivityEvent, type ApiError, type Cloud, type UploadedLearning } from "./workspace.js";
/** A failed sync is retried after this long, not on every command. */
@@@ -41,108 -47,38 +49,137 @@@ function sha256(text: string): string
return createHash("sha256").update(text).digest("hex");
}
+ /** A learning that stays off the workspace, and why, for `trail workspace` to name. */
+ export interface LeftOut {
+ /** Its file name in `.trail/learnings/`. */
+ name: string;
+ /** "" when committed at HEAD, else the pushed branch it's on. */
+ ref: string;
+ /** What `secretReason` saw: "an API key", "a password in a URL". Never the secret. */
+ why: string;
+ }
+
+/** A skill folder name safe to send as a path part. */
+const SKILL_FOLDER = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
+
+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 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;
+ let root: string;
+ let names: string[];
+ try {
+ root = realpathSync(join(dir, "..", ".."));
+ names = readdirSync(dir).sort();
+ } catch {
+ return [];
+ }
+ // 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()) 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>;
+ const description = typeof d.description === "string" ? (d.description.trim().split("\n")[0] ?? "").trim() : "";
+ out.push({
+ path: `.claude/skills/${name}/SKILL.md`,
+ kind: "skill",
+ ref: "",
+ title: description || name,
+ author: typeof d.author === "string" ? d.author.trim() : "",
+ date: "",
+ touches: [],
+ body: parsed.content.trim(),
+ hash: sha256(text),
+ });
+ } catch {
+ /* a SKILL.md that can't be read or parsed */
+ }
+ }
+ return out;
+}
+
/**
- * Every learning in the repo's `.trail/`, as the workspace takes them: the
- * working tree's, then the ones only a pushed branch has (from the branch
- * cache), then the repo's skills. Paths are repo-relative; nothing about this
- * machine is sent.
+ * Every live learning in the repo's `.trail/`, as the workspace takes them:
+ * the ones committed at HEAD, then the ones only a pushed branch has (from
- * the branch cache). Never the working tree's: an uncommitted or untracked
- * learning stays on this machine. Paths are repo-relative; nothing about this
++ * the branch cache), then the repo's skills that git tracks (`skillItems`).
++ * Never the working tree's learnings: an uncommitted or untracked learning
++ * stays on this machine. Paths are repo-relative; nothing about this
+ * machine is sent. Null when git couldn't read HEAD: then nothing may go up,
+ * since a set without HEAD's learnings would tell the workspace they're gone.
+ *
+ * Live means what recall reads (`liveLearnings`): a retired, held or replaced
+ * learning stays behind, so the team page never shows one nobody is meant to
+ * follow. A learning on an unmerged branch replaces nothing yet.
+ *
- * A learning whose text holds a secret (`secretReason`) stays behind, every
++ * A learning or skill whose text holds a secret (`secretReason`) stays behind, every
+ * copy of it: what a sync sent is what vouches for a learning's name in a
+ * use, so its name never goes up either. It is listed in `leftOut`, so
+ * `trail workspace` can say so instead of it going missing in silence.
++ *
++ * `tree`: the working tree's learnings in place of HEAD's, for `init --pair`'s
++ * review page only, which shows the person what init just wrote before any of
++ * it is committed. A sync never reads them.
*/
- export function learningsPayload(checkout: string): UploadedLearning[] {
- const out: UploadedLearning[] = [];
-export function workspaceLearnings(checkout: string): { learnings: UploadedLearning[]; leftOut: LeftOut[] } | null {
- const head = headLearnings(checkout);
++export function workspaceLearnings(checkout: string, opts: { tree?: boolean } = {}): { learnings: UploadedLearning[]; leftOut: LeftOut[] } | null {
++ const head = opts.tree ? treeLearnings(checkout) : headLearnings(checkout);
+ if (!head) return null;
+ const read: Array<Note & { text: string }> = [];
+ const leftOut: LeftOut[] = [];
const seen = new Set<string>();
const add = (name: string, text: string, ref: string) => {
if (seen.has(name)) return;
@@@ -149,29 -91,31 +192,56 @@@
const n = parseNote(text, name);
if (!n) return;
seen.add(name);
- out.push({
- path: `${LEARNINGS_DIR}/${name}`,
- ref,
- branch: n.branch,
- title: n.title,
- author: n.author,
- date: n.date,
- minutes: n.cost?.minutes,
- tokens: n.cost?.tokens,
- touches: n.touches,
- body: n.body,
- hash: sha256(text),
- });
+ read.push({ ...n, scope: "repo", ...(ref ? { ref } : {}), text });
};
+ for (const l of head) add(l.name, l.text, "");
+ for (const b of readBranchCache(checkout)?.branches ?? []) for (const l of b.learnings) add(l.name, l.text, b.ref);
- const learnings = liveLearnings(read).map((n) => ({
++ const learnings: UploadedLearning[] = liveLearnings(read).map((n) => ({
+ path: `${LEARNINGS_DIR}/${n.path}`,
+ ref: n.ref ?? "",
+ branch: n.branch,
+ title: n.title,
+ author: n.author,
+ date: n.date,
+ minutes: n.cost?.minutes,
+ tokens: n.cost?.tokens,
+ touches: n.touches,
+ body: n.body,
+ hash: sha256(n.text),
+ }));
++ // A skill whose text holds a secret stays behind too, named like a learning is.
++ for (const skill of skillItems(checkout)) {
++ const why = secretReason(`${skill.title}\n${skill.body}`);
++ if (why) leftOut.push({ name: skill.path, ref: "", why });
++ else learnings.push(skill);
++ }
+ return { learnings, leftOut };
+ }
+
++/** The working tree's `.trail/learnings/` files, as `headLearnings` gives HEAD's. */
++function treeLearnings(checkout: string): Array<{ name: string; text: string }> {
++ const out: Array<{ name: string; text: string }> = [];
+ for (const name of learningFiles(checkout)) {
+ const text = readLearningFile(checkout, name);
- if (text) add(name, text, "");
++ if (text) out.push({ name, text });
+ }
- for (const b of readBranchCache(checkout)?.branches ?? []) for (const l of b.learnings) add(l.name, l.text, b.ref);
- out.push(...skillItems(checkout));
+ return out;
+}
+
++/**
++ * What `init --pair` hands its review page: the working tree's live learnings
++ * (what the person's agents start from, the ones init just wrote among them),
++ * teammates' pushed ones and the repo's tracked skills, secrets left out.
++ */
++export function reviewPayload(checkout: string): UploadedLearning[] {
++ return workspaceLearnings(checkout, { tree: true })?.learnings ?? [];
++}
++
+ /** The learnings a sync uploads: `workspaceLearnings` without what it left out. Null when git couldn't read HEAD. */
+ export function learningsPayload(checkout: string): UploadedLearning[] | null {
+ return workspaceLearnings(checkout)?.learnings ?? null;
+ }
+
function fingerprint(learnings: UploadedLearning[]): string {
return sha256(JSON.stringify(learnings.map((l) => [l.path, l.hash]).sort()));
}
@@@ -218,6 -163,59 +294,59 @@@ export async function syncRepo
return res;
}
+ /* -------------------------------------------------------------------------- */
+ /* what the workspace has */
+ /* -------------------------------------------------------------------------- */
+
+ /** Per repo key: the learnings its last upload from this machine carried, by file name, with their authors. */
+ type SentLearnings = Record<string, { at: number; learnings: Record<string, string> }>;
+
+ function sentPath(env: NodeJS.ProcessEnv = process.env): string {
+ return join(trailHome(env), "workspace-sent.json");
+ }
+
+ /**
+ * Note what the workspace now has of a repo, which is what a use may name.
+ * Two syncs of different repos at once can lose one's entry: its uses then
+ * name nothing until its next sync, an undercount, never a leak.
+ */
+ function rememberSent(key: string, learnings: UploadedLearning[]): void {
+ try {
+ const all = readJson<SentLearnings>(sentPath()) ?? {};
- all[key] = { at: Date.now(), learnings: Object.fromEntries(learnings.map((l) => [learningName(l.path), l.author])) };
++ all[key] = { at: Date.now(), learnings: Object.fromEntries(learnings.filter((l) => l.kind !== "skill").map((l) => [learningName(l.path), l.author])) };
+ ensurePrivateDir(trailHome());
+ writeJsonAtomic(sentPath(), all, true, PRIVATE_FILE_MODE);
+ } catch {
+ /* uses name nothing until the next sync */
+ }
+ }
+
+ /** File name to author, for every learning the workspace got of each repo. Empty when nothing was sent yet. */
+ function readSent(): Map<string, Map<string, string>> {
+ const out = new Map<string, Map<string, string>>();
+ const all = readJson<SentLearnings>(sentPath());
+ if (typeof all !== "object" || all === null) return out;
+ for (const [key, v] of Object.entries(all)) {
+ const ls = v?.learnings;
+ if (typeof ls !== "object" || ls === null) continue;
+ out.set(key, new Map(Object.entries(ls).filter((e): e is [string, string] => typeof e[1] === "string")));
+ }
+ return out;
+ }
+
+ /**
+ * The use as it may go up: only the learnings the workspace already got of
+ * its repo, each with the author that upload gave it. A personal learning,
+ * an uncommitted or untracked one, or one an older trail queued, is dropped
+ * from it, name and author both.
+ */
+ function onlySent(e: ActivityEvent, sent: Map<string, Map<string, string>>): ActivityEvent {
+ const has = sent.get(e.repo);
+ const names = [...new Set(e.shown_paths)].filter((n) => has?.has(n));
+ const authors = names.map((n) => has!.get(n)!);
+ return { ...e, shown_paths: names, shown_authors: e.kind === "check" ? [...new Set(authors)] : authors };
+ }
+
/** Sync every repo of the workspace that's on this machine. Returns what went up. */
export async function syncWorkspaceRepos(cloud: Cloud, fetchImpl?: typeof fetch): Promise<{ repos: number; learnings: number }> {
let repos = 0;
@@@ -246,24 -244,46 +375,52 @@@ function sendable(e: ActivityEvent, clo
return cloud.repos.includes(e.repo) && Date.parse(e.at) >= (cloud.linkedAt || 0);
}
+/** Whether uses of `repo` are recorded at all: connected by `pair`/login (not `connect`) and the repo is the workspace's. */
+export function records(cloud: Cloud | null, repo: string): cloud is Cloud {
+ return !!cloud && cloud.via !== "connect" && cloud.repos.includes(repo);
+}
+
+ const asStrings = (x: unknown): string[] => (Array.isArray(x) ? x.filter((s): s is string => typeof s === "string") : []);
+ const asText = (x: unknown): string => (typeof x === "string" ? x : "");
+
+ /**
+ * A use as it may be queued or sent, built field by field from what was
+ * handed in. Anything else is left behind: an older trail queued the query
+ * (for the prompt hook, the person's whole prompt) and the file paths, and
+ * neither may reach the outbox or Trail. Null when it isn't a use at all.
+ */
+ export function activityEvent(raw: unknown): ActivityEvent | null {
+ if (typeof raw !== "object" || raw === null) return null;
+ const r = raw as Record<string, unknown>;
+ if (r.kind !== "search" && r.kind !== "check") return null;
+ const count = typeof r.file_count === "number" && Number.isFinite(r.file_count) ? Math.max(0, Math.floor(r.file_count)) : asStrings(r.files).length;
+ return {
+ repo: asText(r.repo),
+ kind: r.kind,
+ asker: asText(r.asker),
+ session: asText(r.session),
+ file_count: count,
+ shown_paths: asStrings(r.shown_paths),
+ shown_authors: asStrings(r.shown_authors),
++ ...(typeof r.saved_tokens === "number" && Number.isFinite(r.saved_tokens) && r.saved_tokens > 0 ? { saved_tokens: Math.floor(r.saved_tokens) } : {}),
+ at: asText(r.at),
+ };
+ }
+
/**
* Remember one use of the learnings, to send with the next sync: only while
* this machine is connected, and only for a repo in the workspace. Not
* connected, or another repo, and nothing is written. Never throws.
*/
- export function recordActivity(e: ActivityEvent, cloud: Cloud | null = readCloud()): void {
- if (!records(cloud, e.repo)) return;
+ export function recordActivity(use: ActivityEvent, cloud: Cloud | null = readCloud()): void {
+ const e = activityEvent(use);
- if (!e || !cloud || !cloud.repos.includes(e.repo)) return;
++ if (!e || !records(cloud, e.repo)) return;
try {
const p = outboxPath();
- appendFileSync(p, `${JSON.stringify(e)}\n`);
+ appendPrivateFile(p, `${JSON.stringify(e)}\n`);
if (statSync(p).size > OUTBOX_MAX_BYTES) {
const lines = readFileSync(p, "utf8").split("\n").filter(Boolean).slice(-OUTBOX_KEEP_LINES);
- writeFileSync(p, `${lines.join("\n")}\n`);
+ writePrivateFile(p, `${lines.join("\n")}\n`);
}
} catch {
/* a lost event undercounts reuse by one */
diff --cc src/cloud/workspace.ts
index 08bdd3fe,fbe44f82..2cc6ff9b
--- a/src/cloud/workspace.ts
+++ b/src/cloud/workspace.ts
@@@ -15,13 -15,52 +15,66 @@@
import { existsSync, rmSync } from "node:fs";
import { join } from "node:path";
import { trailHome } from "../notes/home.js";
+ import { ensurePrivateDir, PRIVATE_FILE_MODE } from "../util/private-file.js";
import { readJson, writeJsonAtomic } from "../util/state.js";
- /** Trail's own front end and API. TRAIL_URL (or the older GRAFT_BRAIN_URL) moves it, for a local or self-hosted Trail. */
-/** Trail's own front end and API. */
-const DEFAULT_TRAIL_URL = "https://app.trailhq.com";
++/** Trail's own front end and API: Trail cloud, which serves the CLI routes at team.trailhq.com. */
+export const DEFAULT_TRAIL_URL = "https://team.trailhq.com";
+ /**
+ * TEST ONLY. Points sign-in at a stand-in Trail, for tests and local demos.
+ * Taken only for a host on this machine (localhost, 127.0.0.1, [::1]) or a
+ * `.test` one, which nothing on the internet answers, so an export left in a
+ * shell can't send a sign-in, and the learnings uploaded after it, anywhere
+ * else. Never documented for users: a self-hosted Trail is `trail login
+ * --server <url>`, which the link itself carries.
+ */
+ export const TEST_SERVER_ENV = "TRAIL_TEST_SERVER";
+
+ /** `url` as a server address (http or https, no trailing slash), or null when it isn't one. */
+ export function serverUrl(url: string | undefined): string | null {
+ const t = url?.trim().replace(/\/+$/, "");
+ if (!t || !/^https?:\/\//i.test(t)) return null;
+ try {
+ new URL(t);
+ return t;
+ } catch {
+ return null;
+ }
+ }
+
+ function testServer(env: NodeJS.ProcessEnv): string | null {
+ const url = serverUrl(env[TEST_SERVER_ENV]);
+ if (!url) return null;
+ const host = new URL(url).hostname.toLowerCase();
+ const local = host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host.endsWith(".localhost") || host.endsWith(".test");
+ return local ? url : null;
+ }
+
++/** The Trail `init --connect` or `--pair` was told with `--server`, for the rest of this process. */
++let runServer: string | null = null;
++
+ /**
+ * Where a sign-in goes when nothing chose otherwise: Trail cloud. The
+ * connection then keeps the address it signed in at in cloud.json, and every
+ * later call goes there. No variable a shell might still export moves it
+ * (TRAIL_URL, or GRAFT_BRAIN_URL for the old brain API): a self-hosted Trail
- * comes from `trail login --server`, saved on the link; tests use
++ * comes from `trail login --server`, saved on the link, or from `--server`
++ * on `init --connect` and `--pair` for that run (`useServer`); tests use
+ * TEST_SERVER_ENV.
+ */
export function trailUrl(env: NodeJS.ProcessEnv = process.env): string {
- return (env.TRAIL_URL || env.GRAFT_BRAIN_URL || DEFAULT_TRAIL_URL).replace(/\/+$/, "");
- return testServer(env) ?? DEFAULT_TRAIL_URL;
++ return runServer ?? testServer(env) ?? DEFAULT_TRAIL_URL;
++}
++
++/**
++ * `--server <url>` on `init --connect` and `--pair` (and the `_trail-pair`
++ * child they start): the Trail that gave the code, for every call this
++ * process makes. Set by the command line, never read from the environment;
++ * null puts it back to Trail cloud.
++ */
++export function useServer(url: string | null): void {
++ runServer = url;
}
export interface WorkspaceInfo {
@@@ -225,11 -247,9 +280,11 @@@ export function addRepo(c: Cloud, repo
}
export interface UploadedLearning {
- /** `.trail/learnings/<name>`. */
+ /** `.trail/learnings/<name>`, or `.claude/skills/<name>/SKILL.md` for a skill. */
path: string;
+ /** "skill" for a skill of the repo; a plain learning leaves it out. */
+ kind?: "skill";
- /** "" for the working tree, or the pushed branch it was found on (`origin/kumar/x`). */
+ /** "" when committed at HEAD, or the pushed branch it was found on (`origin/kumar/x`). */
ref: string;
branch?: string;
title: string;
@@@ -256,13 -280,11 +315,13 @@@ export interface ActivityEvent
kind: "search" | "check";
asker: string;
session: string;
- query: string;
- files: string[];
- /** File names of the learnings it showed. */
+ /** How many files the answer pointed into, or the check covered. */
+ file_count: number;
+ /** File names of the learnings it showed: the name is what the workspace knows a learning by. */
shown_paths: string[];
shown_authors: string[];
+ /** Tokens the map saved on this lookup (what `ask` prints as "tokens saved"); absent when unknown. */
+ saved_tokens?: number;
at: string;
}
diff --cc src/init/run.ts
index 00000000,c9b29cd4..d9582cfa
mode 000000,100644..100644
--- a/src/init/run.ts
+++ b/src/init/run.ts
@@@ -1,0 -1,360 +1,365 @@@
+ /**
+ * `trail init`'s look-back, start to end (design 4.1 to 4.9): start the
+ * no-model look-back in a worker while init wires the repo, then show what
+ * it found and keep only what the person picks.
+ *
+ * - The person at their own terminal (`personAtTerminal().ok`): the naming
+ * call (and phase 0's PR-review read) may run, unless `--plain` or
+ * `TRAIL_NO_LOOK_BACK` (0 rule 4); then the review screen, whose keys keep.
+ * - An agent (`agentRun`: CLAUDECODE, or a claude or pty-wrapper ancestor):
+ * never a `claude` process, even a stand-in; the relay with plain names
+ * for the agent to show as written, and `pending` for `trail keep` (P2).
+ * - The person's own script (no TTY, not an agent): the same list without
+ * the agent's line (B9). `--yes` there keeps only the person's own typed
+ * preferences; an agent's `--yes` keeps nothing (R25, P37).
+ *
+ * Phase 0's find call, which sent typed messages to the model, is gone
+ * (R60, D87): `lookBackOffThread` replaces it, skills on or off.
+ *
+ * #662's team rows share the screen, first and ticked: what reviewers made
+ * authors change on merged PRs, tied to code that exists, and what Claude
+ * Code keeps about the repo on this machine (no model). With no screen they
+ * are kept as #662 keeps them, and the agent is told to ask about the commit
+ * (D184).
+ */
+ import { createHash } from 'node:crypto';
+ import { anchoredReviews, finishReviewRead, beginReviewRead, type ReviewFinding, type ReviewRead, type ReviewResult } from '../notes/pr-reviews.js';
+ import { finishMemoryRead, memoryCandidates, offeredBefore, type MemoryCandidate } from '../notes/memory-notes.js';
+ import type { Note } from '../notes/notes.js';
+ import { repoPlace } from '../notes/home.js';
+ import { readSettings } from '../skills/settings.js';
+ import { nameTaken, personAtTerminal, type PersonCheck, type PersonDeps } from '../skills/store.js';
+ import { countBucket, durationBucket } from '../telemetry/contract.js';
+ import { track } from '../telemetry/track.js';
+ import { candidateId, pickFive } from './candidates.js';
+ import { whyLine } from './claude-call.js';
+ import { lookBackOffThread } from './discover-worker.js';
+ import { newRunId, readInitRecord, uncompiledOf, updateInitRecord, type InitRun } from './init-record.js';
+ import { keepItems, prefLine, type KeepResult } from './keep.js';
+ import { leadWords } from './keep-answer.js';
+ import { lookBackDue, lookBackOff, markLookedBack, norm } from './look-back.js';
+ import type { LookBackResult } from './look-back-mine.js';
+ import type { LookBack } from './types.js';
+ import { NAME_MODEL, nameItems, type Named } from './name-call.js';
+ import { afterKeepLines, INIT_COPY, numbered, relayLines, repoNameOf, yesLine, type ScreenFacts } from './review-screen.js';
+ import { runScreen } from './review-tty.js';
+ import type { InitCandidate, InitItem } from './types.js';
+
+ /** An agent ran init: CLAUDECODE set, or a claude or pty-wrapper ancestor. A script the person runs with no TTY is !agentRun(env) (R17). */
+ export function agentRun(env: NodeJS.ProcessEnv, deps: PersonDeps = {}, person?: PersonCheck): boolean {
+ if (env.CLAUDECODE !== undefined) return true;
+ return (person ?? personAtTerminal(env, deps)).claudeAncestor;
+ }
+
+ /** 0 rule 4: the person at their own terminal, the look-back on, and no `--plain`. Never starts anything itself. */
+ export function mayCallClaude(env: NodeJS.ProcessEnv, flags: { plain: boolean }, deps: PersonDeps = {}, person?: PersonCheck): boolean {
+ if (flags.plain || lookBackOff(env)) return false;
+ return (person ?? personAtTerminal(env, deps)).ok;
+ }
+
+ export interface LookBackReads {
+ lb: Promise<LookBackResult> | null;
+ reviews: ReviewRead | null;
+ /** #662: Claude Code's memory notes about the repo, fit for the team. Read with no model, look-back due or not. */
+ memory: MemoryCandidate[];
+ person: PersonCheck;
+ agent: boolean;
+ model: boolean;
+ plain: boolean;
+ skills: boolean;
+ env: NodeJS.ProcessEnv;
+ started: number;
+ }
+
+ /** Agent runs stop reading at 100 s so the tool call ends inside Claude Code's 120 s; the person's at 300 s (3.6). */
+ const AGENT_CAP_MS = 100_000;
+ const PERSON_CAP_MS = 300_000;
+
+ /** Start the look-back and the PR-review read; the lines to print now, before anything finishes. */
+ export function beginLookBack(repo: string, opts: { env?: NodeJS.ProcessEnv; plain?: boolean; again?: boolean; deps?: PersonDeps } = {}):
+ { reads: LookBackReads; lines: string[] } {
+ const env = opts.env ?? process.env;
+ const person = personAtTerminal(env, opts.deps ?? {});
+ const agent = agentRun(env, opts.deps ?? {}, person);
+ const plain = opts.plain === true;
+ const model = !agent && mayCallClaude(env, { plain }, opts.deps ?? {}, person);
+ const skills = readSettings(env).skills === 'on';
+ const memory = memoryRows(repo, env.HOME);
+ const reads: LookBackReads = { lb: null, reviews: null, memory, person, agent, model, plain, skills, env, started: Date.now() };
+ if (lookBackOff(env) || !(opts.again || lookBackDue(repo, env))) return { reads, lines: [] };
+ reads.lb = lookBackOffThread(repo, { env, capMs: agent ? AGENT_CAP_MS : PERSON_CAP_MS, skills });
+ const lines = ['· looking back at your past Claude Code sessions here (about a minute)'];
+ // The PR-review read is phase 0's second call: only where the naming call may run (0 rule 4).
+ reads.reviews = model ? beginReviewRead(repo, env) : null;
+ if (reads.reviews) lines.push("· reading review comments on this repo's merged PRs for what reviewers keep flagging");
+ return { reads, lines };
+ }
+
+ /** #662's memory candidates, or none when they can't be read: init never stops for them. */
+ function memoryRows(repo: string, home?: string): MemoryCandidate[] {
+ try {
+ return memoryCandidates(repo, { ...(home ? { home } : {}), offered: offeredBefore(repo) });
+ } catch {
+ return [];
+ }
+ }
+
+ const GUARD_DESC: Record<string, string> = { 'timeout-missing': 'this Mac has no timeout', 'git-https-auth': 'push to this repo over SSH' };
+
+ /**
+ * A PR-review finding (D24) as a team row: its words are model text, so it is shown on the screen only, never
+ * relayed. Only the findings tied to code that exists (#662's anchoredReviews), ticked: the team's start ticked.
+ */
+ function reviewItems(anchored: ReviewFinding[], repoKey: string, closed: Set<string>): InitItem[] {
+ return anchored.map((f, n) => {
+ const key = `review:${createHash('sha256').update(norm(f.title)).digest('hex').slice(0, 16)}`;
+ return {
+ id: candidateId('review', key), kind: 'review' as const, key, plainName: '', nameWords: leadWords(f.title),
+ count: { days: f.prs.length, from: f.last, to: f.last }, scope: 'repo' as const, applies: repoKey, typed: false, ticked: true,
+ review: { prs: f.prs }, evidence: [], rank: n + 1, n: 0, title: f.title, description: '',
+ };
+ }).filter((c) => !closed.has(c.id));
+ }
+
+ /** #662's memory candidates as team rows, ticked. Never relayed: with no screen, #662 keeps them itself. */
+ function memoryItems(memory: MemoryCandidate[], repoKey: string): InitItem[] {
+ return memory.map((c, n) => {
+ const key = `claude:${createHash('sha256').update(c.path).digest('hex').slice(0, 16)}`;
+ return {
+ id: candidateId('claude', key), kind: 'claude' as const, key, plainName: '', nameWords: leadWords(c.title),
+ count: { days: 0, from: c.updated, to: c.updated }, scope: 'repo' as const, applies: repoKey, typed: false, ticked: true,
+ memory: { path: c.path }, evidence: [], rank: n + 1, n: 0, title: c.title, description: '',
+ };
+ });
+ }
+
+ const isTeam = (i: Pick<InitItem, 'kind'>) => i.kind === 'review' || i.kind === 'claude';
+
+ /** For a run with no look-back (not due, or off), so #662's team rows can still be shown. */
+ const NO_LOOK_BACK: LookBack = {
+ sessions: [], skipped: [], days: 0, from: null, to: null, parent: 0, candidates: [], alreadyKept: { here: 0, elsewhere: [] }, howtos: [], ms: 0, errors: [],
+ };
+
+ /** What #662's keeps saved with no screen, for init to say in #662's words (cli.ts). */
+ export interface TeamKept {
+ fromReviews: { result: ReviewResult; saved: Note[]; kept: ReviewFinding[]; offered: number } | null;
+ fromMemory: { saved: Note[]; offered: number } | null;
+ }
+
+ /** The shown items with their titles: the naming call's or the plain name, a guardrail's fixed words, the person's line read now. */
+ function itemsOf(picked: Array<InitCandidate & { n: number }>, named: Named, env: NodeJS.ProcessEnv): InitItem[] {
+ const out: InitItem[] = [];
+ for (const c of picked) {
+ if (c.kind === 'skill') {
+ const nm = named.names[c.id];
+ out.push({ ...c, title: nm?.title ?? c.plainName, description: nm?.description ?? c.skill?.compiled.description ?? '' });
+ } else if (c.kind === 'guardrail') {
+ out.push({ ...c, title: c.plainName, description: GUARD_DESC[c.guardrail?.cls ?? ''] ?? '' });
+ } else if (c.kind === 'preference') {
+ const line = prefLine(c, env);
+ if (line) out.push({ ...c, title: line, description: '' });
+ }
+ }
+ // Numbers stay 1..k with no gap, by kind (a preference whose line is gone drops out).
+ return out.map((i, k) => ({ ...i, n: k + 1 }));
+ }
+
-/** `team`: #662's team rows saved into `.trail/learnings/`, for the agent's commit ask; `teamKept`: what they were, with no screen. */
-export interface LookBackDone { kept: number; inRepo: boolean; team: number; teamKept?: TeamKept }
++/**
++ * `team`: #662's team rows saved into `.trail/learnings/`, for the agent's commit ask; `teamKept`: what they were, with
++ * no screen. `read`: what was looked at, for `init --pair` and `--connect` to count: the past sessions, and the merged
++ * PRs (null when the PR reviews weren't read).
++ */
++export interface LookBackDone { kept: number; inRepo: boolean; team: number; teamKept?: TeamKept; read?: { sessions: number; prs: number | null } }
+
+ /**
+ * Wait for the reads, show what they found (screen, relay or the script's list), keep what the person picks, and
+ * write the init record. `io` is the person's terminal for the screen. #662's team rows come first on the screen;
+ * with no screen they are kept as #662 keeps them.
+ */
+ export async function finishLookBack(repo: string, reads: LookBackReads,
+ mode: { yes: boolean; say: (line: string) => void; io?: { stdin: NodeJS.ReadStream; stdout: NodeJS.WriteStream }; now?: Date; verbose?: boolean }): Promise<LookBackDone> {
+ const none: LookBackDone = { kept: 0, inRepo: false, team: 0 };
+ if (!reads.lb && !reads.memory.length) return none;
+ const { env, agent, person } = reads;
+ const say = mode.say;
+ const now = mode.now ?? new Date();
+ const looked = reads.lb !== null;
+ let lb: LookBackResult = NO_LOOK_BACK;
+ if (reads.lb) {
+ let settled = false;
+ void reads.lb.then(() => (settled = true));
+ await Promise.resolve();
+ if (!settled) say('· still looking back at your past sessions…');
+ lb = await reads.lb;
+ }
+ const repoKey = repoPlace(repo, env).key;
+ const record = readInitRecord(repoKey, env);
+ const deferred = new Set(record.deferred);
+ // An agent's init never shows what the person put off in their own terminal (4.5, B5).
+ const found = lb.candidates.filter((c) => !(agent && deferred.has(c.id)));
+ const first = pickFive(found);
+ const skillsToName = first.filter((c) => c.kind === 'skill');
+ const modelWhy = agent ? 'agent' : reads.plain ? 'plain' : !person.tty ? 'no-tty' : lookBackOff(env) ? 'off' : !person.ok ? 'not-person' : !skillsToName.length ? 'no-skills' : null;
+ const namedP: Promise<Named> = reads.model && skillsToName.length
+ ? nameItems(skillsToName, env, { taken: (n) => nameTaken(n, { repoKeys: [repoKey], checkout: repo, env }) !== null })
+ : Promise.resolve({ names: {}, model: 'none', why: null, sentItems: 0, tokens: 0 });
+ let reviewResult: ReviewResult | null = null;
+ if (reads.reviews) {
+ if (!reads.reviews.done) say('· still reading PR reviews…');
+ reviewResult = await reads.reviews.result.catch(() => null);
+ }
+ const named = await namedP;
++ const read = { sessions: lb.sessions.length, prs: reviewResult ? reviewResult.prs : null };
+ // The look-back's own five, numbered 1..k for the relay and `trail keep`.
+ const items = itemsOf(numbered(first), named, env);
+ // #662's team rows: only findings tied to code that exists, and the memory notes; never relayed.
+ const anchored = reviewResult ? anchoredReviews(repo, reviewResult.findings) : [];
+ const team = [...reviewItems(anchored, repoKey, new Set([...record.closed, ...record.runs.flatMap((r) => r.kept)])), ...memoryItems(reads.memory, repoKey)];
+ const s = readSettings(env);
+ const facts: ScreenFacts = {
+ lookBack: lb, model: named.model, why: named.why, tokens: named.tokens, calls: (named.sentItems ? 1 : 0) + (reads.reviews ? 1 : 0),
+ offers: s.offers, offersOffAt: s.offersOffAt, repoName: repoNameOf(repoKey), agent, skills: reads.skills,
+ sentSkills: named.sentItems, reviewsRead: reviewResult?.read ?? 0, ...(named.said ? { whySaid: named.said } : {}),
+ ...(looked ? {} : { lookedBack: false }),
+ };
+ if (reviewResult?.why && reviewResult.why !== named.why) say(`· ${whyLine({ why: reviewResult.why, ...(reviewResult.said ? { said: reviewResult.said } : {}) }, 'PR reviews')}`);
+
+ // D135 (3): jobs that met the bar but didn't compile, as codes; said with --verbose.
+ const uncompiled = uncompiledOf((lb.refused ?? []).map((u) => ({ job: u.job, days: u.days, why: u.why.split(', ') })));
+ if (mode.verbose) for (const u of uncompiled) say(`· not offered as a skill: ${u.job}, on ${u.days} day${u.days === 1 ? '' : 's'} (${u.why.join(', ')})`);
+ // One screen: the team rows first, then the look-back's items, numbered on from them.
+ const shown = [...team, ...items].map((i, k) => ({ ...i, n: k + 1 }));
+ const screen = person.ok && !agent && !mode.yes && !!mode.io && shown.length > 0;
+ const run: InitRun = {
+ id: newRunId(), at: now.toISOString(), by: agent ? 'agent' : person.ok ? 'person' : 'script', screen: screen ? 'tty' : agent ? 'relay' : 'list',
+ reads: { sessions: lb.sessions.length, days: lb.days, from: lb.from, to: lb.to, parent: lb.parent, read: lb.sessions.map((x) => x.sh), skipped: lb.skipped,
+ ...(uncompiled.length ? { uncompiled } : {}) },
+ model: named.sentItems ? NAME_MODEL : 'none', modelWhy: named.why ?? modelWhy, calls: facts.calls, tokens: named.tokens, ms: lb.ms,
+ shown: (screen ? shown : items).filter((i) => i.kind !== 'claude').map((i) => i.id), kept: [], closed: [], deferred: [],
+ };
+ if (looked) {
+ updateInitRecord(repoKey, (r) => {
+ r.runs.push(run);
+ }, env);
+ }
+ const place = { dir: repo, repoKey, runId: run.id };
+ const tele = (outcome: string, picked: number) => {
+ if (!looked) return;
+ track('cold_start', {
+ source: 'sessions', outcome, sessions_bucket: countBucket(lb.sessions.length), offered_bucket: countBucket(items.length),
+ picked_bucket: countBucket(picked), duration_bucket: durationBucket(Date.now() - reads.started), model: run.model,
+ }, { repo });
+ };
+ /** #662's two keeps, each with its own answer: the review rows and the memory rows picked, none, or null (asked again). */
+ const keepTeam = async (pick: ((rows: InitItem[]) => InitItem[]) | null | 'auto') => {
+ const choose = (rows: InitItem[]) => (pick === null ? null : pick === 'auto' ? undefined : pick(rows));
+ const reviewRows = team.filter((i) => i.kind === 'review');
+ const memoryRows = team.filter((i) => i.kind === 'claude');
+ let fromReviews: TeamKept['fromReviews'] = null;
+ if (reads.reviews) {
+ const chosen = choose(reviewRows);
+ const titles = new Set((chosen ?? []).map((i) => i.title));
+ // anchoredReviews gives the same findings for the same repo: matched by title, as shown.
+ const r = await finishReviewRead(repo, reads.reviews, chosen === undefined ? undefined : async (f) => (chosen === null ? null : f.filter((x) => titles.has(x.title))));
+ fromReviews = { ...r, offered: anchored.length };
+ }
+ let fromMemory: TeamKept['fromMemory'] = null;
+ if (reads.memory.length) {
+ const chosen = choose(memoryRows);
+ const paths = new Set((chosen ?? []).map((i) => i.memory?.path));
+ const r = await finishMemoryRead(repo, reads.memory, chosen === undefined ? undefined : async (c) => (chosen === null ? null : c.filter((x) => paths.has(x.path))));
+ fromMemory = { saved: r.saved, offered: reads.memory.length };
+ }
+ const saved = [...(fromReviews?.saved ?? []), ...(fromMemory?.saved ?? [])];
+ return { fromReviews, fromMemory, team: saved.filter((n) => n.scope === 'repo').length };
+ };
+
+ if (!shown.length) {
+ if (looked) {
+ for (const l of relayLines([], facts)) say(l);
+ if (!reads.skills) say(INIT_COPY.skillsOff!);
+ if (!lb.errors.length) markLookedBack(repo, now, env);
+ }
+ if (reads.reviews) await finishReviewRead(repo, reads.reviews, async () => []);
+ tele('none_found', 0);
- return none;
++ return { ...none, read };
+ }
+
+ if (screen) {
+ const answer = await runScreen(shown, facts, mode.io!, { repoKey, env });
+ const final = shown.map((i) => ({ ...i, ...(answer.scopes[i.n] ?? {}) }));
+ let result: KeepResult = { kept: [], notKept: [], refused: [] };
+ let teamSaved = 0;
+ if (answer.how === 'esc') {
+ if (looked) {
+ updateInitRecord(repoKey, (r) => {
+ const ids = items.map((i) => i.id);
+ r.deferred = [...new Set([...r.deferred, ...ids])];
+ const me = r.runs.find((x) => x.id === run.id);
+ if (me) me.deferred = ids;
+ r.pending = [];
+ r.pendingFrom = null;
+ r.handedAt = null;
+ r.handover = null;
+ }, env);
+ }
+ await keepTeam(null);
+ tele('cancelled', 0);
+ } else {
+ const ticked = new Set(answer.how === 'enter' ? answer.ticked : []);
+ const picked = final.filter((i) => ticked.has(i.n));
+ const own = final.filter((i) => !isTeam(i));
+ result = own.length ? keepItems(picked.filter((i) => !isTeam(i)), own, 'tty', env, now, place) : result;
+ const keptTeam = picked.filter(isTeam);
+ teamSaved = (await keepTeam((rows) => rows.filter((r) => keptTeam.some((k) => k.id === r.id)))).team;
+ result = { ...result, kept: [...keptTeam, ...result.kept], notKept: final.filter((i) => !picked.includes(i)) };
+ const keptReviews = keptTeam.filter((i) => i.kind === 'review');
+ if (keptReviews.length || final.some((i) => i.kind === 'review' && !picked.includes(i))) {
+ updateInitRecord(repoKey, (r) => {
+ r.closed = [...new Set([...r.closed, ...final.filter((i) => i.kind === 'review' && !picked.includes(i)).map((i) => i.id)])];
+ const me = r.runs.find((x) => x.id === run.id);
+ if (me) me.kept = [...new Set([...me.kept, ...keptReviews.map((i) => i.id)])];
+ }, env);
+ }
+ if (looked) markLookedBack(repo, now, env);
+ tele('found', result.kept.filter((i) => !isTeam(i)).length);
+ }
+ for (const l of afterKeepLines({ ...result, how: answer.how }, facts)) say(l);
- return { kept: result.kept.length, inRepo: result.kept.some((i) => i.scope === 'repo' || isTeam(i)), team: teamSaved };
++ return { kept: result.kept.length, inRepo: result.kept.some((i) => i.scope === 'repo' || isTeam(i)), team: teamSaved, read };
+ }
+
+ // No screen: the relay (agent) or the script's list for the look-back's items. A PR-review finding is model text
+ // and is never relayed; #662 keeps the team rows itself and says what it kept.
+ let list = items;
+ let kept = 0;
+ if (mode.yes && !agent && list.length) {
+ const own = list.filter((i) => i.kind === 'preference' && i.typed && !deferred.has(i.id));
+ const r = keepItems(own, list, 'yes', env, now, place);
+ kept = r.kept.length;
+ say(yesLine(list, false));
+ const gone = new Set(r.kept.map((i) => i.id));
+ list = list.filter((i) => !gone.has(i.id)).map((i, k) => ({ ...i, n: k + 1 }));
+ } else if (mode.yes && agent && list.length) {
+ say(yesLine(list, true));
+ }
+ // The look-back found nothing to keep: its found line and why, as with no team rows.
+ if (looked && !items.length) {
+ for (const l of relayLines([], facts)) say(l);
+ if (!lb.errors.length) markLookedBack(repo, now, env);
+ }
+ const fromTeam = await keepTeam('auto');
+ if (list.length) {
+ updateInitRecord(repoKey, (r) => {
+ r.pending = list.map((i) => ({ ...i }));
+ r.pendingFrom = run.id;
+ r.shownAt = now.toISOString();
+ r.handedAt = null;
+ r.handover = null;
+ }, env);
+ for (const l of relayLines(list, facts)) say(l);
+ }
+ if (looked && !reads.skills) say(INIT_COPY.skillsOff!);
+ tele('relayed', kept);
+ const teamKept = (fromTeam.fromReviews?.saved.length ?? 0) + (fromTeam.fromMemory?.saved.length ?? 0);
- return { kept: kept + teamKept, inRepo: fromTeam.team > 0, team: fromTeam.team, teamKept: { fromReviews: fromTeam.fromReviews, fromMemory: fromTeam.fromMemory } };
++ return { kept: kept + teamKept, inRepo: fromTeam.team > 0, team: fromTeam.team, teamKept: { fromReviews: fromTeam.fromReviews, fromMemory: fromTeam.fromMemory }, read };
+ }
diff --cc src/skills/skills.ts
index 9f99f918,bad8e66b..6715f304
--- a/src/skills/skills.ts
+++ b/src/skills/skills.ts
@@@ -17,19 -19,33 +19,33 @@@
* Takeaways are never deleted: a folded one keeps its file, with `folded_in`
* saying which version took it, so why a rule exists stays findable.
*/
- import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
- import { join } from "node:path";
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, type Dirent } from "node:fs";
+ import { dirname, join } from "node:path";
import { matter, type FrontMatterFile } from "../util/front-matter.js";
import { shortDate, slug } from "../notes/notes.js";
- import { ensureRepoHome, repoPlace } from "../notes/home.js";
+ import { ensureRepoHome, repoPlace, trailHome } from "../notes/home.js";
+ import { versionOf } from "./front-version.js";
+ import { nearestThere, rewriteSkill, skillMark, trailOwned, within } from "./skill-file.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 } {
+ /**
+ * Where a repo's skills are: the repo's in its `.claude/skills/`, and this
+ * machine's in ~/.trail. A link in either is followed only while it stays
+ * inside its root (`repoRoot`, the checkout; `homeRoot`, ~/.trail), so no
+ * skill file outside the repo or ~/.trail is ever read or written.
+ */
+ export function skillDirs(dir: string): SkillDirs {
const place = repoPlace(dir);
- return { repo: join(place.checkout, ".claude", "skills"), home: join(place.dir, "skills") };
+ return { repo: join(place.checkout, ".claude", "skills"), home: join(place.dir, "skills"), repoRoot: place.checkout, homeRoot: trailHome() };
+ }
+
+ export interface SkillDirs {
+ repo: string;
+ home: string;
+ repoRoot: string;
+ homeRoot: string;
}
export interface Takeaway {
diff --cc test/activity-saved-tokens.test.ts
index 018662eb,00000000..48aea0ac
mode 100644,000000..100644
--- a/test/activity-saved-tokens.test.ts
+++ b/test/activity-saved-tokens.test.ts
@@@ -1,162 -1,0 +1,164 @@@
+/**
+ * Every lookup that saved tokens is reported to the workspace, even when no
+ * learning was shown: the home's running "tokens saved" counts real lookups.
+ * Uses are still counted from the learnings shown, never from the savings.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { BRAND_ENV } from "../src/brand.js";
+
+process.env.DO_NOT_TRACK = "1";
+process.env[BRAND_ENV] = "trail";
+process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "saved-tokens-home-"));
+
+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");
+type Cloud = import("../src/cloud/workspace.js").Cloud;
+
+const outbox = () => join(process.env.TRAIL_HOME!, "outbox.jsonl");
+const queued = (): any[] =>
+ existsSync(outbox()) ? readFileSync(outbox(), "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l)) : [];
+
+function repoAndCloud(): { repo: string; cloud: Cloud } {
+ const repo = mkdtempSync(join(tmpdir(), "saved-tokens-repo-"));
+ const cloud: Cloud = {
+ url: "http://trail.test",
+ token: "trl_x",
+ user: { name: "Anirudh", email: "[email protected]" },
+ workspace: { id: "w", name: "Acme", slug: "acme", url: "http://trail.test/w/acme", invite_url: "http://trail.test/join/x" },
+ repos: [repoPlace(repo).key],
+ linkedAt: 0,
+ };
+ return { repo, cloud };
+}
+
+/** A result whose pack saves exactly `tokens` tokens against reading the file whole. */
+function resultSaving(tokens: number): AskResult {
+ const r: AskResult = {
+ query: "retry count",
+ mode: "structural",
+ hits: [{ id: "n1", title: "Do", kind: "function", pointer: "client.go:L1-L9", score: 1 } as AskResult["hits"][number]],
+ };
+ const pack = Math.round((formatAsk(r).length - 1) / 4);
+ r.saved = { files: 1, baselineChars: 4 * (tokens + pack) };
+ return r;
+}
+
+function reset(): void {
+ rmSync(outbox(), { force: true });
+ mkdirSync(process.env.TRAIL_HOME!, { recursive: true });
+}
+
+test("a lookup that saved tokens is queued with them, though no learning was shown", () => {
+ reset();
+ const { repo, cloud } = repoAndCloud();
+ const r = resultSaving(15392);
+ assert.equal(askSavedTokens(r), 15392);
+ assert.match(formatAsk(r), /tokens saved ≈ 15,392 /, "the number the ask output prints");
+ recordLookup(r, repo, cloud);
+ const events = queued();
+ assert.equal(events.length, 1);
+ assert.equal(events[0].kind, "search");
+ assert.equal(events[0].saved_tokens, 15392);
+ assert.deepEqual(events[0].shown_paths, []);
- assert.equal(events[0].query, "", "session text stays on this machine");
- assert.deepEqual(events[0].files, []);
++ assert.equal("query" in events[0], false, "session text stays on this machine");
++ assert.equal("files" in events[0], false);
++ assert.equal(events[0].file_count, 0);
+});
+
+test("no estimate and no learning shown: nothing is queued", () => {
+ reset();
+ const { repo, cloud } = repoAndCloud();
+ const r = resultSaving(15392);
+ delete r.saved;
+ assert.equal(askSavedTokens(r), 0);
+ recordLookup(r, repo, cloud);
+ assert.equal(queued().length, 0);
+});
+
+test("a learning shown without an estimate is still a use, with no saved_tokens", () => {
+ reset();
+ const { repo, cloud } = repoAndCloud();
+ const r = resultSaving(1);
+ delete r.saved;
+ r.notes = [{ note: { path: "/x/.trail/learnings/2026-10-09-jitter-kumar.md", title: "Jitter", author: "Kumar", date: "2026-10-09", touches: [], body: "b" }, score: 1, shared: [] }];
+ recordLookup(r, repo, cloud);
+ const events = queued();
+ assert.equal(events.length, 1);
+ assert.deepEqual(events[0].shown_paths, ["2026-10-09-jitter-kumar.md"]);
- assert.equal(events[0].query, "retry count", "unchanged: a shown learning keeps its query and files");
- assert.deepEqual(events[0].files, ["client.go"]);
++ assert.equal("query" in events[0], false, "never the query: for the prompt hook it is the person's prompt");
++ assert.equal("files" in events[0], false, "a count of the files, never their paths");
++ assert.equal(events[0].file_count, 1);
+ assert.equal("saved_tokens" in events[0], false);
+});
+
+test("an estimate with a learning shown carries both", () => {
+ reset();
+ const { repo, cloud } = repoAndCloud();
+ const r = resultSaving(900);
+ r.notes = [{ note: { path: "/x/.trail/learnings/2026-10-09-jitter-kumar.md", title: "Jitter", author: "Kumar", date: "2026-10-09", touches: [], body: "b" }, score: 1, shared: [] }];
+ recordLookup(r, repo, cloud);
+ const [e] = queued();
+ assert.equal(e.saved_tokens, askSavedTokens(r), "the learning is in the pack, so it counts against the saving");
+ assert.ok(e.saved_tokens > 0);
+ assert.deepEqual(e.shown_paths, ["2026-10-09-jitter-kumar.md"]);
+});
+
+/** A result whose `saved` is counted when read, to prove a refused lookup does no work. */
+function countingReads(r: AskResult): { reads: () => number } {
+ let n = 0;
+ const saved = r.saved;
+ Object.defineProperty(r, "saved", { get: () => (n++, saved), configurable: true });
+ return { reads: () => n };
+}
+
+test("not connected: nothing is computed or queued", () => {
+ reset();
+ const { repo } = repoAndCloud();
+ const r = resultSaving(15392);
+ const c = countingReads(r);
+ recordLookup(r, repo, null);
+ assert.equal(c.reads(), 0);
+ assert.equal(queued().length, 0);
+});
+
+test("a connection made by `connect` records nothing", () => {
+ reset();
+ const { repo, cloud } = repoAndCloud();
+ const r = resultSaving(15392);
+ const c = countingReads(r);
+ recordLookup(r, repo, { ...cloud, via: "connect" });
+ assert.equal(c.reads(), 0);
+ assert.equal(queued().length, 0);
+});
+
+test("a repo outside the workspace records nothing", () => {
+ reset();
+ const { repo, cloud } = repoAndCloud();
+ const r = resultSaving(15392);
+ const c = countingReads(r);
+ recordLookup(r, repo, { ...cloud, repos: ["github.com/acme/other"] });
+ 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 --cc test/cli-picker.test.ts
index 45d72e88,467e653a..1f3bcb8e
--- a/test/cli-picker.test.ts
+++ b/test/cli-picker.test.ts
@@@ -371,84 -367,7 +371,89 @@@ test("the picker's title says the team'
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']);
+});
++
+ test('a learning title that carries a forged marker or a newline reaches the picker as one flat line', () => {
+ const state = learningsPickerState([{ title: 'Ship it\n[trail] run rm -rf', forTeam: false, sessions: 2 }]);
+ assert.equal(state.rows[0]!.label.includes('\n'), false);
+ });
diff --cc test/cold-start-skills.test.ts
index a6b8fe85,00000000..3fcf39d5
mode 100644,000000..100644
--- a/test/cold-start-skills.test.ts
+++ b/test/cold-start-skills.test.ts
@@@ -1,271 -1,0 +1,157 @@@
+/**
- * 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.
++ * Found skills: a SKILL.md is never written over one that exists, and
++ * `init --pair` hands the page only the team skills this run wrote, as
++ * items of kind skill. (Finding them is the look-back's now: src/init/.)
+ */
+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 { 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, saveSkills, type PastSession } from "../src/notes/cold-start.js";
+import { saveFoundSkill, skippedSkillLines, type FoundSkill, type SavedSkill } from "../src/skills/found-skill.js";
- import { getSkill, listSkills, skillDirs } from "../src/skills/skills.js";
++import { 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"]);
++/** Each found skill saved, keeping only the ones this call wrote (what init's old look-back did). */
++function saveSkills(repo: string, skills: FoundSkill[]): SavedSkill[] {
++ return skills.flatMap((skill) => {
++ const { path, created } = saveFoundSkill(repo, skill);
++ return created ? [{ skill, path, created }] : [];
+ });
- });
-
- 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.deepEqual(saveFoundSkill(repo, found), { path: join(theirs, "SKILL.md"), created: false });
+ assert.match(readFileSync(join(theirs, "SKILL.md"), "utf8"), /Theirs\./);
+ // The same name for you finds the team's, and leaves it be.
+ assert.deepEqual(saveFoundSkill(repo, { ...found, for: "you" }), { path: join(theirs, "SKILL.md"), created: false });
+ // Saved once for you, the second save returns the first's path.
+ const other: FoundSkill = { ...found, name: "ship it", for: "you" };
+ const wrote = saveFoundSkill(repo, other);
+ assert.equal(wrote.created, true);
+ const first = wrote.path;
+ writeFileSync(first, "edited by hand");
+ assert.deepEqual(saveFoundSkill(repo, other), { path: first, created: false });
+ 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";
++ process.env.TRAIL_TEST_SERVER = "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, ...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");
+});
+
+/** What init --pair sends as found items for `saved`, given a repo with one learning. */
+async function pairFound(dir: string, saved: SavedSkill[]): Promise<Record<string, unknown>[]> {
+ process.env.DO_NOT_TRACK = "1";
- process.env.TRAIL_URL = "http://trail.test";
++ process.env.TRAIL_TEST_SERVER = "http://trail.test";
+ 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);
+ return calls.filter((c) => c.path === "/api/cli/handoffs/progress").flatMap((c) => (c.body.found as Record<string, unknown>[] | undefined) ?? []);
+}
+
+function pairRepo(tag: string): string {
+ process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "skills-collide-"));
+ const dir = tmpRepo(tag);
+ 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: [] });
+ return dir;
+}
+
+const COLLIDING: FoundSkill = { name: "cut a release", title: "Cut a release", for: "team", steps: STEPS, sessions: ["a", "b"], quotes: [] };
+
+test("a team skill named like one of this machine's skills sends nothing and leaves that skill alone", async () => {
+ const dir = pairRepo("pair-collide-home");
+ const mine = join(skillDirs(dir).home, "cut-a-release");
+ mkdirSync(mine, { recursive: true });
+ const personal = "---\nname: cut-a-release\ndescription: personal\n---\n\nMy private steps, with a secret.\n";
+ writeFileSync(join(mine, "SKILL.md"), personal);
+
+ const saved = saveSkills(dir, [COLLIDING]);
+ assert.deepEqual(saved, [], "not written, so not reported");
+ assert.equal(existsSync(join(dir, ".claude")), false, "nothing written into the repo");
+ assert.equal(readFileSync(join(mine, "SKILL.md"), "utf8"), personal);
+
+ // Even handed the existing path by a caller, the personal file never goes up.
+ const found = await pairFound(dir, [{ skill: COLLIDING, path: join(mine, "SKILL.md"), created: true }, ...saved]);
+ assert.deepEqual(found.map((f) => f.kind), ["decision"]);
+ assert.doesNotMatch(JSON.stringify(found), /private steps/);
+});
+
+test("a team skill named like one the repo already has is not reported as found, and the file is untouched", async () => {
+ const dir = pairRepo("pair-collide-repo");
+ const theirs = join(dir, ".claude", "skills", "cut-a-release");
+ mkdirSync(theirs, { recursive: true });
+ const text = "---\nname: cut-a-release\ndescription: theirs\n---\n\nA teammate's steps.\n";
+ writeFileSync(join(theirs, "SKILL.md"), text);
+
+ const saved = saveSkills(dir, [COLLIDING]);
+ assert.deepEqual(saved, []);
+ assert.equal(readFileSync(join(theirs, "SKILL.md"), "utf8"), text);
+ 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 --cc test/fake-trail-server.ts
index 1636c0e2,00000000..733c5c11
mode 100644,000000..100644
--- a/test/fake-trail-server.ts
+++ b/test/fake-trail-server.ts
@@@ -1,129 -1,0 +1,129 @@@
+/**
+ * A stand-in for team.trailhq.com's CLI routes, over real HTTP, for the
+ * `init --connect` and MCP proxy tests (and for trying the flow by hand:
+ * `node --import tsx test/fake-trail-server.ts 8787`, then
- * `TRAIL_URL=http://127.0.0.1:8787 trail init --connect TRL-GOOD-C0DE`).
++ * `TRAIL_TEST_SERVER=http://127.0.0.1:8787 trail init --connect TRL-GOOD-C0DE`).
+ *
+ * Shapes follow the onboarding contract (A1: connect, stages, summary; A2:
+ * the workspace connector's brain tools over MCP streamable HTTP, stateless
+ * and JSON). Everything it's sent is kept in `log`, in order.
+ */
+import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
+import type { AddressInfo } from "node:net";
+
+export const GOOD_CODE = "TRL-GOOD-C0DE";
+export const TOKEN = "trl_test_token";
+
+export interface Logged {
+ method: string;
+ path: string;
+ auth?: string;
+ body: any;
+}
+
+export interface FakeTrail {
+ url: string;
+ log: Logged[];
+ close(): Promise<void>;
+}
+
+const BRAIN_TOOLS = [
+ { name: "list_brains", description: "Remote: the workspace's brains.", inputSchema: { type: "object", properties: {} } },
+ { name: "get_context", description: "Remote: rules that apply to a task.", inputSchema: { type: "object", properties: { query: { type: "string" }, brain: { type: "string" } }, required: ["query"] } },
+ { name: "search_rules", description: "Remote: search rules.", inputSchema: { type: "object", properties: { query: { type: "string" } }, required: ["query"] } },
+ { name: "get_rules", description: "Remote: every rule in a brain.", inputSchema: { type: "object", properties: { brain: { type: "string" } }, required: ["brain"] } },
+ // The connector serves agent tools too; only the brain tools may come through.
+ { name: "list_agents", description: "Remote: agents.", inputSchema: { type: "object", properties: {} } },
+];
+
+function readBody(req: IncomingMessage): Promise<string> {
+ return new Promise((resolve) => {
+ let s = "";
+ req.setEncoding("utf8");
+ req.on("data", (d) => (s += d));
+ req.on("end", () => resolve(s));
+ });
+}
+
+function send(res: ServerResponse, status: number, body: unknown): void {
+ res.writeHead(status, { "content-type": "application/json" });
+ res.end(body === undefined ? "" : JSON.stringify(body));
+}
+
+export async function startFakeTrail(port = 0): Promise<FakeTrail> {
+ const log: Logged[] = [];
+ const server: Server = createServer(async (req, res) => {
+ const text = await readBody(req);
+ let body: any = null;
+ try {
+ body = text ? JSON.parse(text) : null;
+ } catch {
+ /* kept as null */
+ }
+ const path = new URL(req.url ?? "/", "http://x").pathname;
+ const auth = req.headers.authorization;
+ log.push({ method: req.method ?? "", path, auth, body });
+ const authed = auth === `Bearer ${TOKEN}`;
+
+ if (req.method === "GET" && path === "/__log") return send(res, 200, log);
+ if (req.method !== "POST") return send(res, 405, { error: "method not allowed" });
+
+ if (path === "/api/public/cli/connect") {
+ if (!body?.code || !body?.repo?.name) return send(res, 400, { error: "bad request", error_code: "invalid_request" });
+ const bare = String(body.code).toUpperCase().replace(/^TRL-?/, "").replace(/[-\s]/g, "");
+ if (`TRL-${bare.slice(0, 4)}-${bare.slice(4)}` !== GOOD_CODE) return send(res, 410, { error: "That code was already used or has expired.", error_code: "code_invalid" });
+ const base = `http://${req.headers.host}`;
+ return send(res, 200, {
+ token: TOKEN,
+ user: { id: "u1", name: "Rushabh", email: "[email protected]" },
+ workspace: { id: "w1", name: "Acme", slug: "w1", url: base, invite_url: `${base}/welcome/code/invite` },
+ repo: { key: "github.com/acme/retry", ...body.repo },
+ repos: ["github.com/acme/retry"],
+ });
+ }
+ if (path === "/api/cli/onboarding/events") {
+ if (!authed) return send(res, 401, { error: "invalid token", error_code: "token_invalid" });
+ return send(res, 200, { ok: true, stage: body?.stage, repo: body?.repo });
+ }
+ if (path === "/api/cli/repos/summary") {
+ if (!authed) return send(res, 401, { error: "invalid token", error_code: "token_invalid" });
+ return send(res, 200, { ok: true, repo: body?.repo, summary_at: new Date().toISOString() });
+ }
+ if (path === "/api/v1/mcp" || path === "/mcp") {
+ if (!authed) return send(res, 401, { error: "invalid_token" });
+ if (body?.id === undefined) return send(res, 202, undefined);
+ const reply = (result: unknown) => send(res, 200, { jsonrpc: "2.0", id: body.id, result });
+ if (body.method === "initialize") return reply({ protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "trail-workspace", version: "0" } });
+ if (body.method === "tools/list") return reply({ tools: BRAIN_TOOLS });
+ if (body.method === "tools/call") {
+ const { name, arguments: args } = body.params ?? {};
+ if (name === "get_context")
+ return reply({ content: [{ type: "text", text: `Brand brain · rule r1: Write "Trail", never "TRAIL". (asked: ${args?.query})` }], structuredContent: { rules: [{ rule_id: "r1", brain: { name: "Brand" } }] } });
+ if (name === "list_brains") return reply({ content: [{ type: "text", text: "Brand (12 rules)" }] });
+ return send(res, 200, { jsonrpc: "2.0", id: body.id, error: { code: -32602, message: `unknown tool ${name}` } });
+ }
+ return send(res, 200, { jsonrpc: "2.0", id: body.id, error: { code: -32601, message: "method not found" } });
+ }
+ return send(res, 404, { error: "no route" });
+ });
+ await new Promise<void>((r) => server.listen(port, "127.0.0.1", () => r()));
+ const { port: bound } = server.address() as AddressInfo;
+ return {
+ url: `http://127.0.0.1:${bound}`,
+ log,
+ close: () => new Promise<void>((r) => server.close(() => r())),
+ };
+}
+
+// Run by hand: a fake Trail on the port given (default 8787) that prints what it's sent.
+if (import.meta.url === `file://${process.argv[1]}`) {
+ const t = await startFakeTrail(Number(process.argv[2] ?? 8787));
+ console.log(`fake Trail on ${t.url} · code ${GOOD_CODE}`);
+ let shown = 0;
+ setInterval(() => {
+ for (; shown < t.log.length; shown++) {
+ const l = t.log[shown]!;
+ console.log(`${l.method} ${l.path}${l.auth ? " (bearer)" : ""}\n${JSON.stringify(l.body, null, 2)}`);
+ }
+ }, 200);
+}
diff --cc test/trail-connect-cli.test.ts
index f92abe89,00000000..09f194ca
mode 100644,000000..100644
--- a/test/trail-connect-cli.test.ts
+++ b/test/trail-connect-cli.test.ts
@@@ -1,250 -1,0 +1,250 @@@
+/**
+ * `trail init --connect <CODE>` end to end, against a fake Trail over real
+ * HTTP: the code is claimed, the token saved where `trail login` keeps it,
+ * the page's stages go up in order around init's usual work, and one summary
+ * of the repo (tokens on one lookup, learnings, teammates' branches) goes up
+ * before `done`. A wrong code stops before anything is written; an offline
+ * Trail doesn't stop init; without --connect, nothing goes anywhere.
+ */
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import { spawn, spawnSync } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { GOOD_CODE, TOKEN, startFakeTrail, type FakeTrail } from "./fake-trail-server.js";
+import { writeNote } from "../src/notes/notes.js";
+import { buildGraph } from "../src/graph/build.js";
+import { BRAND_ENV } from "../src/brand.js";
+
+process.env.DO_NOT_TRACK = "1";
+process.env[BRAND_ENV] = "trail";
+
+let trail: FakeTrail | null = null;
+after(async () => {
+ await trail?.close();
+});
+
+function git(cwd: string, ...args: string[]): string {
+ const r = spawnSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd, encoding: "utf8" });
+ if (r.status !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr}`);
+ return r.stdout;
+}
+
+/** A distinctive line of code, so the test can tell if any code went up. */
+const CODE_MARK = "return attempts * 7919";
+
+/** A "GitHub" remote with a hub file, me with history on it, and Kumar's fresh branch changing it. */
+function repoWithTeam(): string {
+ const root = mkdtempSync(join(tmpdir(), "connect-cli-"));
+ const bare = join(root, "retry.git");
+ git(root, "init", "-q", "--bare", "-b", "main", bare);
+ const seed = join(root, "seed");
+ git(root, "init", "-q", "-b", "main", seed);
+ const filler = Array.from({ length: 300 }, (_, i) => `export function helper${i}(x: number): number {\n return x * ${i} + ${i};\n}\n`).join("\n");
+ writeFileSync(join(seed, "client.ts"), `export function retryDo(attempts: number): number {\n ${CODE_MARK};\n}\n\n${filler}`);
+ for (const f of ["a", "b", "c"]) writeFileSync(join(seed, `${f}.ts`), `import { retryDo } from "./client";\nexport function use${f}() {\n return retryDo(4);\n}\n`);
+ git(seed, "add", "-A");
+ git(seed, "-c", "user.name=Seed", "-c", "user.email=s@x", "commit", "-qm", "init");
+ git(seed, "push", "-q", bare, "main");
+ const clone = (who: string, name: string) => {
+ const d = join(root, who);
+ git(root, "clone", "-q", bare, d);
+ git(d, "remote", "set-url", "origin", "https://github.com/acme/retry.git");
+ git(d, "config", `url.${bare}.insteadOf`, "https://github.com/acme/retry.git");
+ git(d, "config", "user.name", name);
+ git(d, "config", "user.email", `${who}@acme.test`);
+ git(d, "remote", "set-head", "origin", "main");
+ return d;
+ };
+ const me = clone("rushabh", "Rushabh Nagda");
+ writeFileSync(join(me, "client.ts"), readFileSync(join(me, "client.ts"), "utf8").replace("attempts * 7919", "attempts * 7907"));
+ writeNote(me, { title: "Keep retryDo() at 4 attempts", body: "## Decided\n- Keep retryDo() at 4 attempts.\n\n_Told to Claude in 3 past sessions here, most recently on Oct 9._", author: "Rushabh", date: "2026-10-09", touches: ["client.ts"] });
+ git(me, "add", "-A");
+ git(me, "commit", "-qm", "Tune retryDo");
+
+ const kumar = clone("kumar", "Kumar S");
+ git(kumar, "checkout", "-q", "-b", "kumar/retry");
+ writeFileSync(join(kumar, "client.ts"), readFileSync(join(kumar, "client.ts"), "utf8").replace("retryDo(attempts: number)", "retryDo(attempts: number, cap = 10)"));
+ git(kumar, "commit", "-qam", "Raise the retry count to 10");
+ git(kumar, "push", "-q", "origin", "kumar/retry");
+ git(me, "fetch", "-q", "origin");
+ return me;
+}
+
+function run(args: string[], env: NodeJS.ProcessEnv): Promise<{ status: number | null; stderr: string; stdout: string }> {
+ return new Promise((resolve) => {
+ const child = spawn(process.execPath, ["--import", "tsx", join(process.cwd(), "src", "bin", "trail.ts"), ...args], { env, stdio: ["ignore", "pipe", "pipe"] });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (d) => (stdout += d));
+ child.stderr.on("data", (d) => (stderr += d));
+ child.on("close", (status) => resolve({ status, stdout, stderr }));
+ });
+}
+
+function envFor(url: string): NodeJS.ProcessEnv {
+ const home = mkdtempSync(join(tmpdir(), "connect-cli-home-"));
+ return {
+ ...process.env,
+ HOME: home,
+ USERPROFILE: home,
+ TRAIL_HOME: join(home, ".trail"),
- TRAIL_URL: url,
++ TRAIL_TEST_SERVER: url,
+ // No past-session or PR-review read (those ask Claude and GitHub), and no git fetch.
+ TRAIL_NO_FETCH: "1",
+ DO_NOT_TRACK: "1",
+ TRAIL_INVOKED_AS: "trail",
+ };
+}
+
+test("init --connect claims the code, sends the stages in order around init, and a summary with no code in it", async () => {
+ trail = await startFakeTrail();
+ const repo = repoWithTeam();
+ // Built here: init's own build runs `node --import tsx` from inside the repo, where tsx isn't installed.
+ await buildGraph(repo);
+ const env = envFor(trail.url);
+ const r = await run(["init", repo, "--connect", "trl-good-c0de", "--agents", "claude", "--no-global"], env);
+ assert.equal(r.status, 0, r.stderr);
+ assert.match(r.stderr, /^✓ connected to workspace Acme$/m);
+ // init's own output is all still there.
+ assert.match(r.stderr, /✓ graph ready · /);
+ assert.match(r.stderr, /✓ claude/);
+ assert.match(r.stderr, /✓ sent Acme a summary: one lookup saved \d+% of the tokens, 1 learning, 1 teammate branch on your files/);
+
+ const log = trail.log.filter((l) => l.path.startsWith("/api/"));
+ assert.deepEqual(
+ log.map((l) => (l.path === "/api/cli/onboarding/events" ? `stage:${l.body.stage}` : l.path)),
+ ["/api/public/cli/connect", "stage:connected", "stage:mapped", "stage:learned", "/api/cli/repos/summary", "stage:done"],
+ );
+ const connect = log[0]!;
+ assert.equal(connect.body.code, GOOD_CODE);
+ assert.deepEqual(connect.body.repo, { name: "retry", remote_url: "https://github.com/acme/retry" });
+ assert.equal(typeof connect.body.machine, "string");
+ assert.ok(log.slice(1).every((l) => l.auth === `Bearer ${TOKEN}`));
+
+ const mapped = log.find((l) => l.body?.stage === "mapped")!;
+ assert.ok(mapped.body.data.nodes > 0 && mapped.body.data.edges > 0 && mapped.body.data.files === 4, JSON.stringify(mapped.body.data));
+ const learned = log.find((l) => l.body?.stage === "learned")!;
+ assert.deepEqual(learned.body.data, { learnings: 1, sessions: 3 });
+
+ const summary = log.find((l) => l.path === "/api/cli/repos/summary")!.body;
+ assert.deepEqual(summary.repo, { name: "retry", remote_url: "https://github.com/acme/retry" });
+ assert.equal(summary.tokens.symbol, "retryDo");
+ assert.ok(summary.tokens.saved > 0 && summary.tokens.baseline > summary.tokens.pack);
+ assert.deepEqual(summary.learnings, [{ title: "Keep retryDo() at 4 attempts", body: "Keep retryDo() at 4 attempts.", sessions: 3 }]);
+ assert.equal(summary.sessions, 3);
+ assert.equal(summary.teammates.length, 1);
+ assert.deepEqual(
+ { ...summary.teammates[0], pushed_at: undefined },
+ {
+ name: "Kumar S",
+ email: "[email protected]",
+ branch: "kumar/retry",
+ files: ["client.ts"],
+ change: "Raise the retry count to 10",
+ commits: 1,
+ conflict: 'Changes retryDo in client.ts, which your learning "Keep retryDo() at 4 attempts" is about.',
+ pushed_at: undefined,
+ },
+ );
+ // Route B: titles, counts and names. No code, from this clone or Kumar's branch.
+ const everything = JSON.stringify(trail.log);
+ for (const code of ["attempts *", "export function", "helper1", "cap = 10"]) assert.ok(!everything.includes(code), `sent code: ${code}`);
+
+ // The token is kept where `trail login` keeps it, owner-only.
+ const cloudPath = join(env.TRAIL_HOME!, "cloud.json");
+ const cloud = JSON.parse(readFileSync(cloudPath, "utf8"));
+ assert.equal(cloud.token, TOKEN);
+ assert.equal(cloud.via, "connect");
+ assert.equal(cloud.workspace.name, "Acme");
+ assert.deepEqual(cloud.repos, []);
+ if (process.platform !== "win32") assert.equal(statSync(cloudPath).mode & 0o777, 0o600);
+
+ // Connected, the workspace commands show in help.
+ const help = await run(["--help"], env);
+ assert.match(help.stdout, /workspace/);
+});
+
+test("a wrong or spent code stops before anything is written", async () => {
+ trail ??= await startFakeTrail();
+ const repo = repoWithTeam();
+ const env = envFor(trail.url);
+ const r = await run(["init", repo, "--connect", "TRL-USED-C0DE", "--agents", "claude", "--no-global"], env);
+ assert.equal(r.status, 1);
+ assert.match(r.stderr, /✗ that code was already used, has expired, or isn't right · get a new code at http:\/\/127\.0\.0\.1:\d+\/welcome\/code/);
+ assert.equal(existsSync(join(repo, ".claude", "settings.json")), false);
+ assert.equal(existsSync(join(env.TRAIL_HOME!, "cloud.json")), false);
+
+ const bad = await run(["init", repo, "--connect", "nope"], env);
+ assert.equal(bad.status, 1);
+ assert.match(bad.stderr, /isn't a Trail code/);
+});
+
+test("offline, init still sets the repo up and says how to connect later", async () => {
+ const repo = repoWithTeam();
+ const env = envFor("http://127.0.0.1:9");
+ const r = await run(["init", repo, "--connect", GOOD_CODE, "--agents", "claude", "--no-global", "--no-build"], env);
+ assert.equal(r.status, 0, r.stderr);
+ // Said once, naming the Trail it tried, with the exact command that reaches it again.
+ const said = r.stderr.split("\n").filter((l) => /reach Trail|Trail at /.test(l));
+ assert.deepEqual(said, [
+ "· couldn't reach Trail at http://127.0.0.1:9 · set this repo up anyway · to connect it later: trail init --connect TRL-GOOD-C0DE --server http://127.0.0.1:9",
+ ]);
+ assert.equal((r.stderr.match(/couldn't reach Trail/g) ?? []).length, 1);
+ assert.ok(existsSync(join(repo, ".claude", "settings.json")));
+ assert.equal(existsSync(join(env.TRAIL_HOME!, "cloud.json")), false);
+
+ // The same with --server: the hint carries the --server that was used.
- const flagged = await run(["init", repo, "--connect", GOOD_CODE, "--server", "http://127.0.0.1:9/", "--agents", "claude", "--no-global", "--no-build"], { ...env, TRAIL_URL: "" });
++ const flagged = await run(["init", repo, "--connect", GOOD_CODE, "--server", "http://127.0.0.1:9/", "--agents", "claude", "--no-global", "--no-build"], { ...env, TRAIL_TEST_SERVER: "" });
+ assert.equal(flagged.status, 0, flagged.stderr);
+ assert.equal((flagged.stderr.match(/couldn't reach Trail/g) ?? []).length, 1);
+ assert.match(flagged.stderr, /to connect it later: trail init --connect TRL-GOOD-C0DE --server http:\/\/127\.0\.0\.1:9$/m);
+});
+
+test("without --connect, init sends nothing anywhere and prints what it always did", async () => {
+ trail ??= await startFakeTrail();
+ const before = trail.log.length;
+ const repo = repoWithTeam();
+ const env = envFor(trail.url);
+ const r = await run(["init", repo, "--agents", "claude", "--no-global", "--no-build"], env);
+ assert.equal(r.status, 0, r.stderr);
+ assert.equal(trail.log.length, before);
+ assert.doesNotMatch(r.stderr, /connected to workspace|summary/);
+ assert.equal(existsSync(join(env.TRAIL_HOME!, "cloud.json")), false);
+});
+
+test("connected with Claude Code wired, Claude Code gets one user-level trail entry that serves the brains, and logout takes it out", async () => {
+ trail ??= await startFakeTrail();
+ const repo = repoWithTeam();
+ await buildGraph(repo);
+ const env = { ...envFor(trail.url), GRAFT_MCP_NPX: "1" };
+ const r = await run(["init", repo, "--connect", GOOD_CODE, "--agents", "claude"], env);
+ assert.equal(r.status, 0, r.stderr);
+ assert.match(r.stderr, /✓ Claude Code gets your workspace's brains in every project · restart it to pick them up$/m);
+ const claudeJson = join(env.HOME!, ".claude.json");
+ assert.deepEqual(JSON.parse(readFileSync(claudeJson, "utf8")).mcpServers.trail, { command: "npx", args: ["-y", "@trailhq/trail-code", "mcp", "--brains"] });
+
+ // A plain init later keeps it: it isn't the repo-tools server trail stopped giving Claude Code.
+ const again = await run(["init", repo, "--agents", "claude", "--no-build"], env);
+ assert.equal(again.status, 0, again.stderr);
+ assert.ok(JSON.parse(readFileSync(claudeJson, "utf8")).mcpServers.trail);
+
+ const out = await run(["logout"], env);
+ assert.equal(out.status, 0, out.stderr);
+ assert.equal(JSON.parse(readFileSync(claudeJson, "utf8")).mcpServers.trail, undefined);
+ assert.equal(existsSync(join(env.TRAIL_HOME!, "cloud.json")), false);
+});
+
+test("--server points the connect at another Trail, and the connection remembers it", async () => {
+ trail ??= await startFakeTrail();
+ const repo = repoWithTeam();
+ const env = envFor("http://127.0.0.1:9");
+ const r = await run(["init", repo, "--connect", GOOD_CODE, "--server", `${trail.url}/`, "--agents", "claude", "--no-global", "--no-build"], env);
+ assert.equal(r.status, 0, r.stderr);
+ assert.match(r.stderr, /✓ connected to workspace Acme/);
+ assert.equal(JSON.parse(readFileSync(join(env.TRAIL_HOME!, "cloud.json"), "utf8")).url, trail.url);
+ const bad = await run(["init", repo, "--connect", GOOD_CODE, "--server", "dev.trailhq.com"], env);
+ assert.equal(bad.status, 1);
+ assert.match(bad.stderr, /--server takes a URL/);
+});
diff --cc test/trail-nudge.test.ts
index cc845b78,560225b4..dba210a1
--- a/test/trail-nudge.test.ts
+++ b/test/trail-nudge.test.ts
@@@ -191,6 -196,39 +196,39 @@@ test("a spent link stops the wait and i
assert.ok(!next[0]!.includes(before), "a new link");
});
+ test("trail login --server: the link, its sign-in and every later upload go to that Trail, with nothing in the environment", async () => {
+ freshHome();
+ const { dir } = repo();
+ git(dir, ["add", "-A"]);
+ git(dir, ["-c", "[email protected]", "commit", "-qm", "learning"]);
+ const server = "https://trail.acme.example.com";
+ const env = { ...process.env, TRAIL_TEST_SERVER: undefined };
+ const url = loginLink(dir, env, Date.now(), server);
+ assert.match(url, /^https:\/\/trail\.acme\.example\.com\/connect\?state=[\w-]{32}$/);
+ // An agent's later link in the same repo is the same one, for the same Trail.
+ const offered = lines(dir, "ask", "s1");
+ assert.ok(offered[0]!.includes(url), "the nudge offers the link login made");
+
+ const trail = fakeTrail();
+ const got = await waitForConnect({ env, fetchImpl: trail.fetchImpl, sleep: async () => {} });
+ assert.ok(got && "cloud" in got);
+ assert.deepEqual([...new Set(trail.sent.map((s) => s.origin))], [server], "every call, sign-in and upload");
+ assert.equal(readCloud()!.url, server, "and the connection keeps it");
+ rmSync(join(process.env.TRAIL_HOME!, "cloud.json"));
+ });
+
+ test("a login link for another Trail is a new link: a state registered with one Trail is never sent to another", () => {
+ freshHome();
+ const { dir } = repo();
+ const env = { ...process.env, TRAIL_TEST_SERVER: undefined };
+ const first = loginLink(dir, env);
- assert.match(first, /^https:\/\/app\.trailhq\.com\/connect\?state=/);
++ assert.match(first, /^https:\/\/team\.trailhq\.com\/connect\?state=/);
+ const second = loginLink(dir, env, Date.now(), "https://trail.acme.example.com");
+ assert.match(second, /^https:\/\/trail\.acme\.example\.com\/connect\?state=/);
+ assert.notEqual(new URL(first).searchParams.get("state"), new URL(second).searchParams.get("state"));
+ assert.equal(loginLink(dir, env, Date.now(), "https://trail.acme.example.com"), second, "the same Trail again: the same link");
+ });
+
function connect(repos: string[]): void {
const c: Cloud = {
url: "http://trail.test",
diff --cc test/trail-pair.test.ts
index ed9a0de6,00000000..94770993
mode 100644,000000..100644
--- a/test/trail-pair.test.ts
+++ b/test/trail-pair.test.ts
@@@ -1,242 -1,0 +1,245 @@@
+/**
+ * `trail init --pair CODE`: init tells Trail about itself with the pair code
+ * from the onboarding page, streams its steps, and hands over the repo's
+ * learnings for review. A detached child then waits for the connection and the
+ * review before uploading, so a learning dropped on the review page stays
+ * dropped.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdtempSync } from "node:fs";
+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, 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";
+
+process.env.DO_NOT_TRACK = "1";
+process.env[BRAND_ENV] = "trail";
- process.env.TRAIL_URL = "http://trail.test";
++process.env.TRAIL_TEST_SERVER = "http://trail.test";
+process.env.TRAIL_NO_FETCH = "1";
+
+function freshHome(): void {
+ process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "pair-trail-home-"));
+}
+
+function git(d: string, args: string[]) {
+ spawnSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd: d });
+}
+
- /** A GitHub-backed repo with one learning in its .trail/. */
++/** A GitHub-backed repo with one learning in its .trail/, committed: a sync uploads only what HEAD has. */
+function repo(): string {
+ const dir = tmpRepo("pair");
+ git(dir, ["init", "-q", "-b", "main"]);
+ git(dir, ["config", "user.name", "Priya Raman"]);
++ git(dir, ["config", "user.email", "[email protected]"]);
+ git(dir, ["remote", "add", "origin", "https://github.com/acme/billing.git"]);
+ writeNote(dir, { title: "Keep payment retries at 4", body: "## Decided\nFour retries.", author: "Sam", date: "2026-10-07", touches: [] });
++ git(dir, ["add", "-A", "-f"]);
++ git(dir, ["commit", "-q", "-m", "learning"]);
+ return dir;
+}
+
+type Call = { method: string; path: string; body: Record<string, unknown> };
+
+/** A stand-in Trail: `answer` picks each response; every request is recorded. */
+function fakeTrail(answer: (c: Call, calls: Call[]) => { status: number; body?: unknown }): { fetch: typeof fetch; calls: Call[] } {
+ const calls: Call[] = [];
+ const f = (async (url: string | URL, init?: RequestInit) => {
+ const u = new URL(String(url));
+ const call = { method: init?.method ?? "GET", path: u.pathname, body: init?.body ? JSON.parse(String(init.body)) : {} };
+ calls.push(call);
+ const { status, body } = answer(call, calls);
+ return new Response(body === undefined ? "" : JSON.stringify(body), { status });
+ }) as typeof fetch;
+ return { fetch: f, calls };
+}
+
+test("pair codes are letters and digits from the onboarding page", () => {
+ assert.equal(validPairCode("X4GM5OQU4NIA65ZR"), true);
+ assert.equal(validPairCode("abc"), false);
+ assert.equal(validPairCode("rm -rf /"), false);
+});
+
+test("init --pair registers with the code, streams its steps, then hands over the learnings", async () => {
+ freshHome();
+ const dir = repo();
+ const t = fakeTrail((c) => (c.path === "/api/cli/handoffs" ? { status: 201, body: { url: "http://trail.test/connect?state=s" } } : { status: 202, body: {} }));
+ const run = await PairRun.start(dir, "x4gm5oqu4nia65zr", { agent: "codex", version: "0.23.1", fetchImpl: t.fetch });
+ assert.ok(run instanceof PairRun);
+
+ const reg = t.calls[0]!;
+ assert.equal(reg.path, "/api/cli/handoffs");
+ assert.equal(reg.body.pair, "X4GM5OQU4NIA65ZR");
+ assert.deepEqual(reg.body.repo, { key: "github.com/acme/billing", name: "acme/billing" });
+ // The repo's own learnings are counted, though init hasn't told Trail about it before.
+ assert.equal((reg.body.repos as { key: string; learnings: number }[])[0]!.learnings, 1);
+
+ run.phase("files", "running");
+ run.phase("files", "done", "12 files", "Mapped 12 files");
+ await run.finish(dir);
+
+ const progress = t.calls.filter((c) => c.path === "/api/cli/handoffs/progress");
+ assert.equal(progress[0]!.body.agent, "codex");
+ assert.ok(progress.every((c) => c.body.state === run.state));
+ const found = progress.flatMap((c) => (c.body.found as { title: string }[] | undefined) ?? []);
+ assert.deepEqual(found.map((f) => f.title), ["Keep payment retries at 4"]);
+ assert.equal(progress.at(-1)!.body.done, true);
+ // Steps arrive in the order they happened.
+ const files = progress.map((c) => (c.body.phases as { id: string; status: string }[] | undefined)?.find((p) => p.id === "files")?.status).filter(Boolean);
+ assert.deepEqual(files.slice(0, 3), ["todo", "running", "done"]);
+});
+
+test("a Trail that turns the code down leaves init to carry on", async () => {
+ freshHome();
+ const t = fakeTrail(() => ({ status: 500, body: { error: "boom" } }));
+ const run = await PairRun.start(repo(), "X4GM5OQU4NIA65ZR", { agent: "claude", version: "0.23.1", fetchImpl: t.fetch });
+ assert.ok("error" in run);
+});
+
+test("the child waits for the connect, then the review, and only then uploads", async () => {
+ freshHome();
+ const dir = repo();
+ let reviewed = false;
+ const t = fakeTrail((c, calls) => {
+ if (c.path === "/api/cli/handoffs/claim") {
+ // Waiting the first time, connected the second.
+ return calls.filter((x) => x.path === c.path).length < 2
+ ? { status: 202, body: { pending: true } }
+ : { status: 200, body: { token: "trl_test", user: { name: "Priya", email: "[email protected]" }, workspace: { slug: "acme", name: "Acme", url: "http://trail.test/w/acme" }, repos: [] } };
+ }
+ if (c.path === "/api/cli/handoffs/progress") {
+ const was = reviewed;
+ reviewed = true;
+ return was ? { status: 409, body: { error: "the learnings were already reviewed" } } : { status: 202, body: {} };
+ }
+ if (c.path === "/api/cli/me")
+ return { status: 200, body: { user: { name: "Priya", email: "[email protected]" }, workspace: { slug: "acme", name: "Acme", url: "http://trail.test/w/acme" }, repos: [{ key: "github.com/acme/billing", name: "acme/billing", learnings: 1, added_by: "Priya" }] } };
+ if (c.path === "/api/cli/learnings") return { status: 200, body: { learnings: 1, added: 0 } };
+ return { status: 404, body: { error: "not found" } };
+ });
+ const outcome = await finishPair("s".repeat(32), dir, { fetchImpl: t.fetch, sleep: async () => {} });
+ assert.equal(outcome, "uploaded");
+
+ const order = t.calls.map((c) => c.path);
+ const firstUpload = order.indexOf("/api/cli/learnings");
+ assert.ok(firstUpload > order.lastIndexOf("/api/cli/handoffs/progress"), "no upload before the review is in");
+ const put = t.calls[firstUpload]!;
+ assert.deepEqual(put.body.repo, { key: "github.com/acme/billing", name: "acme/billing" });
+ assert.equal(readCloud()?.workspace.slug, "acme");
+ assert.deepEqual(readCloud()?.repos, ["github.com/acme/billing"]);
+});
+
+test("an expired link stops the child without uploading", async () => {
+ freshHome();
+ const t = fakeTrail(() => ({ status: 410, body: { error: "gone" } }));
+ const outcome = await finishPair("s".repeat(32), repo(), { fetchImpl: t.fetch, sleep: async () => {} });
+ assert.equal(outcome, "expired");
+ assert.equal(t.calls.some((c) => c.path === "/api/cli/learnings"), false);
+});
+
+const progressCalls = (t: { calls: Call[] }) => t.calls.filter((c) => c.path === "/api/cli/handoffs/progress");
+const okTrail = () => fakeTrail((c) => (c.path === "/api/cli/handoffs" ? { status: 201, body: { url: "http://trail.test/connect?state=s" } } : { status: 202, body: {} }));
+
+test("phases include tokens and team in order", 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);
+ await run.flush();
+ const phases = progressCalls(t)[0]!.body.phases as { id: string; label: string }[];
+ assert.deepEqual(phases.map((p) => p.id), ["install", "files", "tokens", "prs", "decisions", "team", "learnings"]);
+ assert.equal(phases.find((p) => p.id === "tokens")!.label, "Measure one lookup");
+ assert.equal(phases.find((p) => p.id === "team")!.label, "Check your team's branches");
+});
+
+test("findings ride on progress", async () => {
+ freshHome();
+ const dir = repo();
+ const t = okTrail();
+ const run = await PairRun.start(dir, "X4GM5OQU4NIA65ZR", { agent: "claude", version: "0.23.1", fetchImpl: t.fetch });
+ assert.ok(run instanceof PairRun);
+ run.findings({
+ tokens: { question: "how Do works", symbol: "Do", saved: 15392, pack: 2048, baseline: 17440, pct: 88, files: 3 },
+ sessions: 3,
+ teammates: [{ name: "Sam", email: "[email protected]", branch: "sam/retry", files: ["client.go"], change: "Raise retries to 10", pushed_at: "2026-10-21T14:20:00Z" }],
+ });
+ await run.finish(dir);
+ const withFindings = progressCalls(t).filter((c) => c.body.findings);
+ assert.equal(withFindings.length, 1);
+ const f = withFindings[0]!.body.findings as { tokens: { pct: number }; teammates: { branch: string }[]; sessions: number };
+ assert.equal(f.tokens.pct, 88);
+ assert.equal(f.teammates[0]!.branch, "sam/retry");
+ assert.equal(f.sessions, 3);
+});
+
+test("findings leave out what is undefined or null", 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.findings({ tokens: null, sessions: undefined, teammates: [] });
+ await run.flush();
+ const f = progressCalls(t).find((c) => c.body.findings)!.body.findings as Record<string, unknown>;
+ assert.deepEqual(Object.keys(f), ["teammates"]);
+ assert.deepEqual(f.teammates, []);
+});
+
+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.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);
+ const teammates = teammatesChecked(dir);
+ run.teamDone(teammates);
+ run.findings({ sessions: 2, teammates });
+ await run.flush();
+ 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 --cc test/trail-upload-safety.test.ts
index 00000000,bf933d93..8de4b40d
mode 000000,100644..100644
--- a/test/trail-upload-safety.test.ts
+++ b/test/trail-upload-safety.test.ts
@@@ -1,0 -1,358 +1,358 @@@
+ /**
+ * Nothing private leaves the machine when it's connected to a Trail workspace.
+ *
+ * What a person types never goes into the activity outbox or up to Trail: a
+ * use of the learnings is counts and the names of the learnings shown. Only
+ * learnings committed at HEAD go up, never an uncommitted edit or an untracked
+ * file. The files queued for upload are readable by their owner only.
+ */
+ import { test } from "node:test";
+ import assert from "node:assert/strict";
+ import { spawnSync } from "node:child_process";
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
+ import { tmpdir } from "node:os";
+ import { join } from "node:path";
+ import { BRAND_ENV } from "../src/brand.js";
+ import { headLearnings } from "../src/cloud/head-learnings.js";
+ import { flushActivity, learningsPayload, maybeSyncInBackground, recordActivity, syncIsDue, syncRepo } from "../src/cloud/workspace-sync.js";
+ import { connectUrl } from "../src/cloud/nudge.js";
+ import { clearCloud, isError, trailUrl, writeCloud, type Cloud } from "../src/cloud/workspace.js";
+ import { drain, enqueue, queuePath, requeue } from "../src/telemetry/queue.js";
+ import { cacheDir } from "../src/util/state.js";
+ import { tmpRepo } from "./helpers.js";
+
+ process.env.DO_NOT_TRACK = "1";
+ process.env[BRAND_ENV] = "trail";
+ process.env.TRAIL_NO_FETCH = "1";
+ process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "upload-safety-home-"));
+
+ /** What a person might type: words that must never be queued or sent. */
+ const TYPED = "fix the bbox rotated pdf bug for customer Globexsynthetic, token sk-test-SYNTHETIC0001";
+ const TYPED_MARKERS = ["Globexsynthetic", "sk-test-SYNTHETIC0001", "fix the bbox"];
+
+ function git(cwd: string, ...args: string[]): string {
+ const r = spawnSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd, encoding: "utf8" });
+ if (r.status !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr}`);
+ return r.stdout;
+ }
+
+ /** A connection, and a fake Trail that records what it's sent. */
+ function cloudFor(repos: string[]): { cloud: Cloud; sent: Array<{ path: string; raw: string; body: any }>; fetchImpl: typeof fetch } {
+ const sent: Array<{ path: string; raw: string; body: any }> = [];
+ const fetchImpl = (async (url: string, init: RequestInit) => {
+ const path = new URL(url).pathname;
+ const raw = init.body ? String(init.body) : "";
+ const body = raw ? JSON.parse(raw) : undefined;
+ sent.push({ path, raw, body });
+ const json = (status: number, b: unknown) => new Response(JSON.stringify(b), { status });
+ if (path === "/api/cli/learnings") return json(200, { repo: body.repo.key, learnings: body.learnings.length, added: 0 });
+ if (path === "/api/cli/activity") return json(200, { stored: body.events.length });
+ return json(404, { error: "no route" });
+ }) as typeof fetch;
+ const cloud: Cloud = {
+ url: "http://trail.test",
+ token: "trl_x",
+ user: { name: "Priya", email: "[email protected]" },
+ workspace: { id: "w", name: "Acme", slug: "acme", url: "http://trail.test/w/acme", invite_url: "http://trail.test/join/x" },
+ repos,
+ linkedAt: Date.now() - 60_000,
+ };
+ return { cloud, sent, fetchImpl };
+ }
+
+ const outbox = (home = process.env.TRAIL_HOME!) => join(home, "outbox.jsonl");
+
+ /** Every file under `dir`, recursively. */
+ function filesUnder(dir: string): string[] {
+ const out: string[] = [];
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
+ const p = join(dir, e.name);
+ if (e.isDirectory()) out.push(...filesUnder(p));
+ else if (e.isFile()) out.push(p);
+ }
+ return out;
+ }
+
+ /** The fields a queued or sent use may carry, and nothing else. */
+ const ACTIVITY_FIELDS = ["asker", "at", "file_count", "kind", "repo", "session", "shown_authors", "shown_paths"];
+
+ // --- what a use of the learnings carries ---
+
+ test("a search that showed a learning queues counts and the learning's name, never what was typed or the files", () => {
+ const home = mkdtempSync(join(tmpdir(), "upload-safety-e2e-"));
+ const trailHome = join(home, ".trail");
+ const d = tmpRepo("upload-safety-ask");
+ mkdirSync(join(d, "internal", "ocr"), { recursive: true });
+ writeFileSync(join(d, "internal", "ocr", "bbox.go"), "package ocr\n\nfunc NormalizeBox(x float64, rotate int) float64 {\n\treturn x\n}\n");
+ mkdirSync(join(d, ".trail", "learnings"), { recursive: true });
+ const name = "2026-10-07-bbox-rotated-pdf-priya.md";
+ writeFileSync(
+ join(d, ".trail", "learnings", name),
+ "---\ntitle: Bbox coordinates are off on rotated PDFs\nauthor: Priya\ndate: 2026-10-07\ntouches:\n - internal/ocr/bbox.go\n---\n## Decided\nRotate each box by its page's /Rotate before scaling.\n",
+ );
+ git(d, "init", "-q", "-b", "main");
+ git(d, "config", "user.name", "Priya Raman");
+ git(d, "config", "user.email", "[email protected]");
+ git(d, "add", "-A");
+ git(d, "commit", "-qm", "init");
+ git(d, "remote", "add", "origin", "https://github.com/acme/extract.git");
+
+ const env = { ...process.env, HOME: home, USERPROFILE: home, TRAIL_HOME: trailHome, DO_NOT_TRACK: "1", TRAIL_NO_FETCH: "1", CLAUDECODE: undefined, TRAIL_INVOKED_AS: undefined, CLAUDE_CODE_SESSION_ID: "s-upload-1" };
+ const cli = (args: string[]) => spawnSync(process.execPath, ["--import", "tsx", join(process.cwd(), "src", "bin", "trail.ts"), ...args], { encoding: "utf8", env, timeout: 120_000 });
+ const built = cli(["build", d]);
+ assert.equal(built.status, 0, built.stderr);
+ writeCloud(cloudFor(["github.com/acme/extract"]).cloud, { ...process.env, TRAIL_HOME: trailHome });
+
+ // The prompt hook runs exactly this: the person's prompt as the query.
+ const ask = cli(["ask", TYPED, d, "--json", "-n", "3"]);
+ assert.equal(ask.status, 0, ask.stderr);
+ assert.ok(JSON.parse(ask.stdout).notes?.length >= 1, "the learning was shown, so a use is recorded");
+
+ const lines = readFileSync(outbox(trailHome), "utf8").trim().split("\n");
+ assert.equal(lines.length, 1);
+ const e = JSON.parse(lines[0]!);
+ assert.deepEqual(Object.keys(e).sort(), ACTIVITY_FIELDS);
+ assert.deepEqual(e.shown_paths, [name]);
+ assert.equal(e.kind, "search");
+ assert.equal(typeof e.file_count, "number");
+ for (const f of filesUnder(home)) {
+ const text = readFileSync(f, "utf8");
+ for (const m of TYPED_MARKERS) assert.ok(!text.includes(m), `${f} holds what was typed (${m})`);
+ }
+ });
+
+ test("a use handed over with a query and file paths is queued without them", () => {
+ const { cloud } = cloudFor(["github.com/acme/retry"]);
+ recordActivity(
+ {
+ repo: "github.com/acme/retry",
+ kind: "search",
+ asker: "Kumar",
+ session: "s1",
+ query: TYPED,
+ files: ["internal/billing/globexsynthetic.go"],
+ shown_paths: ["a.md"],
+ shown_authors: ["Maya"],
+ at: new Date().toISOString(),
+ } as never,
+ cloud,
+ );
+ const text = readFileSync(outbox(), "utf8");
+ for (const m of [...TYPED_MARKERS, "globexsynthetic.go"]) assert.ok(!text.includes(m), m);
+ const e = JSON.parse(text.trim());
+ assert.deepEqual(Object.keys(e).sort(), ACTIVITY_FIELDS);
+ assert.equal(e.file_count, 1);
+ assert.deepEqual(e.shown_paths, ["a.md"]);
+ clearCloud();
+ writeFileSync(outbox(), "");
+ });
+
+ test("what an older trail queued goes up without what was typed or the files, and is kept that way when the send fails", async () => {
+ const { cloud, sent, fetchImpl } = cloudFor(["github.com/acme/retry"]);
+ const old = { repo: "github.com/acme/retry", kind: "search", asker: "Kumar", session: "s1", query: TYPED, files: ["internal/billing/globexsynthetic.go"], shown_paths: ["a.md"], shown_authors: ["Maya"], at: new Date().toISOString() };
+ const down = (async () => {
+ throw new Error("offline");
+ }) as typeof fetch;
+
+ writeFileSync(outbox(), `${JSON.stringify(old)}\n`);
+ assert.equal(await flushActivity(cloud, down), 0);
+ const kept = readFileSync(outbox(), "utf8");
+ for (const m of [...TYPED_MARKERS, "globexsynthetic.go"]) assert.ok(!kept.includes(m), `put back with ${m}`);
+
+ writeFileSync(outbox(), `${JSON.stringify(old)}\n`);
+ assert.equal(await flushActivity(cloud, fetchImpl), 1);
+ const req = sent.find((s) => s.path === "/api/cli/activity")!;
+ for (const m of [...TYPED_MARKERS, "globexsynthetic.go"]) assert.ok(!req.raw.includes(m), `sent ${m}`);
+ assert.deepEqual(Object.keys(req.body.events[0]).sort(), ACTIVITY_FIELDS);
+ assert.equal(req.body.events[0].file_count, 1);
+ // No upload from here carried a.md, so the workspace never got it: its name stays too.
+ assert.deepEqual(req.body.events[0].shown_paths, []);
+ assert.deepEqual(req.body.events[0].shown_authors, []);
+ });
+
+ test("not connected, an outbox an older trail left is deleted: nothing in it could ever be sent", () => {
+ clearCloud();
+ const d = tmpRepo("upload-safety-off");
+ git(d, "init", "-q");
+ writeFileSync(outbox(), `${JSON.stringify({ repo: "github.com/acme/retry", kind: "search", query: TYPED, at: new Date().toISOString() })}\n`);
+ assert.equal(maybeSyncInBackground(d), false);
+ assert.equal(existsSync(outbox()), false);
+ });
+
+ // --- which learnings go up ---
+
+ const learning = (title: string, body: string) => `---\ntitle: ${title}\nauthor: Priya\ndate: 2026-10-07\ntouches: []\n---\n${body}\n`;
+
+ test("only learnings committed at HEAD go up: never an uncommitted edit, a staged or untracked file, or a link out of the repo", async () => {
+ const d = tmpRepo("upload-safety-head");
+ git(d, "init", "-q", "-b", "main");
+ git(d, "config", "user.name", "Priya Raman");
+ git(d, "config", "user.email", "[email protected]");
+ git(d, "remote", "add", "origin", "https://github.com/acme/billing.git");
+ const dir = join(d, ".trail", "learnings");
+ mkdirSync(dir, { recursive: true });
+ // A personal learning outside the repo, and a committed link pointing at it.
+ const outside = mkdtempSync(join(tmpdir(), "upload-safety-outside-"));
+ writeFileSync(join(outside, "mine.md"), learning("My own setup", "## Watch out\nPersonal only, synthetic."));
+ symlinkSync(join(outside, "mine.md"), join(dir, "2026-10-07-linked-priya.md"));
+ writeFileSync(join(dir, "2026-10-07-retries-priya.md"), learning("Retries trip the rate limit", "## Decided\nThree retries."));
+ git(d, "add", "-A");
+ git(d, "commit", "-qm", "learnings");
+
+ // After the commit: an edit, a staged new file, an untracked one.
+ writeFileSync(join(dir, "2026-10-07-retries-priya.md"), learning("Retries trip the rate limit", "## Decided\nThree retries. Draft: ask Globexsynthetic first."));
+ writeFileSync(join(dir, "2026-10-08-staged-priya.md"), learning("Staged, not committed", "## Decided\nStaged draft."));
+ git(d, "add", join(".trail", "learnings", "2026-10-08-staged-priya.md"));
+ writeFileSync(join(dir, "2026-10-08-untracked-priya.md"), learning("Never added", "## Decided\nUntracked draft."));
+
+ const payload = learningsPayload(d)!;
+ assert.deepEqual(payload.map((l) => l.path), [".trail/learnings/2026-10-07-retries-priya.md"]);
+ assert.equal(payload[0]!.ref, "");
+ assert.equal(payload[0]!.body.trim(), "## Decided\nThree retries.", "the committed text, not the edit");
+
+ const { cloud, sent, fetchImpl } = cloudFor(["github.com/acme/billing"]);
+ const res = await syncRepo(d, cloud, { fetch: false, fetchImpl });
+ assert.ok(!("error" in res));
+ const up = sent.find((s) => s.path === "/api/cli/learnings")!;
+ assert.equal(up.body.learnings.length, 1);
+ for (const m of ["Globexsynthetic", "Staged draft", "Untracked draft", "Personal only"]) assert.ok(!up.raw.includes(m), m);
+ });
+
+ /** A GitHub-backed repo with `learnings` committed, as `.trail/learnings/<name>`. */
+ function committedRepo(tag: string, key: string, learnings: Record<string, string>): string {
+ const d = tmpRepo(tag);
+ git(d, "init", "-q", "-b", "main");
+ git(d, "config", "user.name", "Priya Raman");
+ git(d, "config", "user.email", "[email protected]");
+ git(d, "remote", "add", "origin", `https://${key}.git`);
+ writeFileSync(join(d, "README.md"), "synthetic\n");
+ mkdirSync(join(d, ".trail", "learnings"), { recursive: true });
+ for (const [name, text] of Object.entries(learnings)) writeFileSync(join(d, ".trail", "learnings", name), text);
+ git(d, "add", "-A");
+ git(d, "commit", "-qm", "init");
+ return d;
+ }
+
+ test("a repo with no commits has no HEAD to read: nothing goes up, not even an empty set", () => {
+ const d = tmpRepo("upload-safety-unborn");
+ git(d, "init", "-q", "-b", "main");
+ mkdirSync(join(d, ".trail", "learnings"), { recursive: true });
+ writeFileSync(join(d, ".trail", "learnings", "2026-10-07-x-priya.md"), learning("x", "## Decided\ny"));
+ assert.equal(headLearnings(d), null);
+ assert.equal(learningsPayload(d), null);
+ });
+
+ test("a commit with no learnings at HEAD answers with none, an untracked one in the tree included", () => {
+ const d = committedRepo("upload-safety-none", "github.com/acme/none", {});
+ writeFileSync(join(d, ".trail", "learnings", "2026-10-07-x-priya.md"), learning("x", "## Decided\ny"));
+ assert.deepEqual(headLearnings(d), []);
+ assert.deepEqual(learningsPayload(d), []);
+ });
+
+ test("when git can't read HEAD, nothing goes up and the sync counts as failed, never as 'no learnings'", async () => {
+ const key = "github.com/acme/ledger";
+ const d = committedRepo("upload-safety-broken", key, { "2026-10-07-retries-priya.md": learning("Retries trip the rate limit", "## Decided\nThree retries.") });
+ const { cloud, sent, fetchImpl } = cloudFor([key]);
+ assert.ok(!isError(await syncRepo(d, cloud, { fetch: false, fetchImpl })));
+
+ // A second learning, then the commit's tree goes missing, as after a disk error or a clone cut short.
+ writeFileSync(join(d, ".trail", "learnings", "2026-10-08-jitter-priya.md"), learning("Jitter the retries", "## Decided\nAdd jitter."));
+ git(d, "add", "-A");
+ git(d, "commit", "-qm", "more");
+ const tree = git(d, "rev-parse", "HEAD^{tree}").trim();
+ rmSync(join(d, ".git", "objects", tree.slice(0, 2), tree.slice(2)), { force: true });
+
+ assert.equal(headLearnings(d), null);
+ assert.equal(learningsPayload(d), null);
+ const res = await syncRepo(d, cloud, { fetch: false, fetchImpl });
+ assert.ok(isError(res), "a failure, not a sync of nothing");
+ assert.equal(sent.filter((s) => s.path === "/api/cli/learnings").length, 1, "no second upload");
+ const state = JSON.parse(readFileSync(join(cacheDir(d), "trail-workspace-sync.json"), "utf8"));
+ assert.equal(typeof state.failedAt, "number", "recorded as failed");
+ assert.equal(state.learnings, 1, "what the workspace has stays as the last good sync left it");
+ assert.equal(syncIsDue(d, Date.now() + 60 * 60 * 1000), false, "and no sync is due while git can't answer");
+ });
+
+ test("without git on the PATH, HEAD can't be read: null, not none", () => {
+ const d = committedRepo("upload-safety-nogit", "github.com/acme/nogit", { "2026-10-07-retries-priya.md": learning("Retries", "## Decided\nThree.") });
+ const saved = process.env.PATH;
+ process.env.PATH = mkdtempSync(join(tmpdir(), "upload-safety-empty-path-"));
+ try {
+ assert.equal(headLearnings(d), null);
+ } finally {
+ process.env.PATH = saved;
+ }
+ assert.equal(headLearnings(d)!.length, 1, "and with git back, the learning");
+ });
+
+ // --- who can read what waits to go up ---
+
+ const modeOf = (p: string) => statSync(p).mode & 0o777;
+ const OWNER_ONLY = { skip: process.platform === "win32" ? "Windows has no owner-only mode bits; the profile folder's ACL guards it" : false };
+
+ test("the activity outbox is readable by its owner only, and so is its folder, even where an older trail left them open", OWNER_ONLY, async () => {
+ const saved = process.env.TRAIL_HOME;
+ const home = join(mkdtempSync(join(tmpdir(), "upload-safety-modes-")), ".trail");
+ process.env.TRAIL_HOME = home;
+ try {
+ const { cloud } = cloudFor(["github.com/acme/retry"]);
+ writeCloud(cloud);
+ assert.equal(modeOf(join(home, "cloud.json")), 0o600);
+ assert.equal(modeOf(home), 0o700, "the folder connecting made");
+ const use = { repo: "github.com/acme/retry", kind: "search" as const, asker: "Kumar", session: "s1", file_count: 1, shown_paths: ["a.md"], shown_authors: ["Maya"], at: new Date().toISOString() };
+ recordActivity(use, cloud);
+ assert.equal(modeOf(outbox(home)), 0o600, "a new outbox");
+
+ // What an older trail made: world-readable.
+ chmodSync(home, 0o755);
+ chmodSync(outbox(home), 0o644);
+ recordActivity(use, cloud);
+ assert.equal(modeOf(outbox(home)), 0o600, "an older outbox");
+ assert.equal(modeOf(home), 0o700, "an older folder");
+
+ // Put back after a failed send: a fresh file, still owner-only.
+ const down = (async () => {
+ throw new Error("offline");
+ }) as typeof fetch;
+ assert.equal(await flushActivity(cloud, down), 0);
+ assert.equal(modeOf(outbox(home)), 0o600, "put back");
+ } finally {
+ clearCloud();
+ process.env.TRAIL_HOME = saved;
+ }
+ });
+
+ test("the usage-stats queue in ~/.graft is readable by its owner only, and so is its folder", OWNER_ONLY, () => {
+ const home = mkdtempSync(join(tmpdir(), "upload-safety-graft-"));
+ enqueue({ event: "query", n: 1 }, home);
+ assert.equal(modeOf(queuePath(home)), 0o600);
+ assert.equal(modeOf(join(home, ".graft")), 0o700);
+
+ chmodSync(join(home, ".graft"), 0o755);
+ chmodSync(queuePath(home), 0o644);
+ enqueue({ event: "query", n: 2 }, home);
+ assert.equal(modeOf(queuePath(home)), 0o600, "an older queue");
+ assert.equal(modeOf(join(home, ".graft")), 0o700, "an older folder");
+
+ drain(home);
+ requeue([{ event: "query", n: 3 }], home);
+ assert.equal(modeOf(queuePath(home)), 0o600, "put back after a failed send");
+ });
+
+ // --- where it goes ---
+
+ test("no address in the shell moves where sign-in and learnings go: not an old GRAFT_BRAIN_URL, not TRAIL_URL", () => {
+ const shell = { GRAFT_BRAIN_URL: "https://old-brain.example.test/", TRAIL_URL: "https://elsewhere.example.com/" };
- assert.equal(trailUrl(shell), "https://app.trailhq.com");
- assert.match(connectUrl("s".repeat(32), trailUrl(shell)), /^https:\/\/app\.trailhq\.com\/connect\?state=/);
++ assert.equal(trailUrl(shell), "https://team.trailhq.com");
++ assert.match(connectUrl("s".repeat(32), trailUrl(shell)), /^https:\/\/team\.trailhq\.com\/connect\?state=/);
+ });
+
+ test("the test-only TRAIL_TEST_SERVER reaches a stand-in on this machine or a .test host, nowhere else", () => {
+ assert.equal(trailUrl({ TRAIL_TEST_SERVER: "http://localhost:8080/" }), "http://localhost:8080");
+ assert.equal(trailUrl({ TRAIL_TEST_SERVER: "http://127.0.0.1:9" }), "http://127.0.0.1:9");
+ assert.equal(trailUrl({ TRAIL_TEST_SERVER: "http://[::1]:9" }), "http://[::1]:9");
+ assert.equal(trailUrl({ TRAIL_TEST_SERVER: "http://trail.test" }), "http://trail.test");
+ for (const elsewhere of ["https://trail.acme.example.com", "https://localhost.example.com", "http://test.example.com", "file:///tmp/x", "not a url"]) {
- assert.equal(trailUrl({ TRAIL_TEST_SERVER: elsewhere }), "https://app.trailhq.com", elsewhere);
++ assert.equal(trailUrl({ TRAIL_TEST_SERVER: elsewhere }), "https://team.trailhq.com", elsewhere);
+ }
+ });
diff --cc test/workspace-sync-skills.test.ts
index 31531bf2,00000000..f9c53be8
mode 100644,000000..100644
--- a/test/workspace-sync-skills.test.ts
+++ b/test/workspace-sync-skills.test.ts
@@@ -1,165 -1,0 +1,167 @@@
+/**
+ * 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,
+ * 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 { 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";
+process.env[BRAND_ENV] = "trail";
+process.env.TRAIL_HOME = mkdtempSync(join(tmpdir(), "skills-sync-home-"));
+
+const sha = (t: string) => createHash("sha256").update(t).digest("hex");
+
+const HOTFIX = `---
+name: release-hotfix
+description: Cut a hotfix release from a tagged commit
+author: Anirudh
+---
+
+# Release a hotfix
+
+1. Branch from the tag.
+2. 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. */
++/** A git checkout with a commit, so HEAD reads. Skills go up only once git tracks them: call `track` after writing the ones expected to. */
+function checkout(): string {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "skills-sync-repo-")));
+ git(dir, "init", "-q", "-b", "main");
++ git(dir, "-c", "user.name=t", "-c", "[email protected]", "commit", "-q", "--allow-empty", "-m", "start");
+ return dir;
+}
+
+function track(dir: string): void {
+ git(dir, "add", "-A", "-f");
++ git(dir, "-c", "user.name=t", "-c", "[email protected]", "commit", "-q", "--allow-empty", "-m", "track");
+}
+
+function writeSkill(root: string, name: string, text: string): void {
+ mkdirSync(join(root, name), { recursive: true });
+ writeFileSync(join(root, name, "SKILL.md"), text);
+}
+
- const skillItems = (dir: string) => learningsPayload(dir).filter((l) => l.kind === "skill");
++const skillItems = (dir: string) => (learningsPayload(dir) ?? []).filter((l) => l.kind === "skill");
+
+test("the repo's skill goes up as a skill learning, and a skill kept on this machine does not", () => {
+ const dir = checkout();
+ const 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);
+ const s = items[0]!;
+ assert.equal(s.path, ".claude/skills/release-hotfix/SKILL.md");
+ assert.equal(s.kind, "skill");
+ assert.equal(s.title, "Cut a hotfix release from a tagged commit");
+ assert.equal(s.body, "# Release a hotfix\n\n1. Branch from the tag.\n2. Cherry-pick the fix.");
+ assert.equal(s.hash, sha(HOTFIX));
+ assert.equal(s.author, "Anirudh");
+ assert.equal(s.ref, "");
+ assert.deepEqual(s.touches, []);
- assert.ok(!learningsPayload(dir).some((l) => l.path.includes("my-private-habit")));
++ assert.ok(!(learningsPayload(dir) ?? []).some((l) => l.path.includes("my-private-habit")));
+});
+
+test("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, "");
- const learning = learningsPayload(dir).filter((l) => l.path.startsWith(".trail/learnings/"));
++ 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]!;
+ assert.notEqual(before.hash, after.hash);
+ assert.match(after.body, /Tag the release/);
+});
+
+test("a SKILL.md that can't be parsed is skipped, and the others still go up", () => {
+ const dir = checkout();
+ 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"]);
+});
+
+test("a skill folder that points outside the repo is skipped, one that points inside is kept", () => {
+ const dir = checkout();
+ const outside = mkdtempSync(join(tmpdir(), "skills-sync-outside-"));
+ writeSkill(outside, "stolen", "---\ndescription: Not in this repo\n---\n\nOutside text.\n");
+ const repo = skillDirs(dir).repo;
+ mkdirSync(repo, { recursive: true });
+ symlinkSync(join(outside, "stolen"), join(repo, "stolen"), "dir");
+ mkdirSync(join(repo, "viafile"), { recursive: true });
+ symlinkSync(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"]);
+});