feat(init): end init with a snapshot of the user's repo and one prompt to paste (#4871)

Replaces the five-command 'Next steps' list with a local, time-capped snapshot
(tracked files, top languages, most-changed code file over 90 days, test
command) and one ready-to-paste Claude Code prompt about that file. git runs
with argument arrays and a 2s timeout; any failure prints the generic prompt.
Skipped for --format json and --start-all/--start-daemon.

Co-authored-by: r <r@x>
This commit is contained in:
rUvandr authored and GitHub committed 2026-11-06 14:41:05 -06:00
1 parent 2d700b957a
commit c29732ed35
3 files changed
+183 -14

No files matched your search

@@ -0,0 +1,68 @@
/**
* Adoption plan item 1: `init` ends with a snapshot of the user's own repo and
* one prompt to paste into Claude Code. The snapshot is local-only and must
* never fail init, so the null paths matter as much as the happy path.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { execFileSync } from 'child_process';
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { snapshotProject, snapshotLines, firstPrompt } from '../src/init/first-win.js';
const git = (cwd: string, ...args: string[]) =>
execFileSync('git', ['-c', 'user.email=t@t', '-c', 'user.name=t', '-c', 'commit.gpgsign=false', ...args], { cwd, stdio: 'ignore' });
describe('init first win', () => {
let repo: string;
let plain: string;
beforeAll(() => {
repo = mkdtempSync(join(tmpdir(), 'firstwin-'));
plain = mkdtempSync(join(tmpdir(), 'firstwin-plain-'));
git(repo, 'init', '-q');
mkdirSync(join(repo, 'src'));
writeFileSync(join(repo, 'package.json'), JSON.stringify({ scripts: { test: 'vitest run' } }));
writeFileSync(join(repo, 'src', 'b.ts'), 'export const b = 1;\n');
for (let i = 0; i < 3; i++) {
writeFileSync(join(repo, 'src', 'hot.ts'), `export const v = ${i};\n`);
writeFileSync(join(repo, 'README.md'), `# r${i}\n`); // churns too, but is not code
git(repo, 'add', '-A');
git(repo, 'commit', '-q', '-m', `c${i}`);
}
});
afterAll(() => {
rmSync(repo, { recursive: true, force: true });
rmSync(plain, { recursive: true, force: true });
});
it('summarises a git repo and points the prompt at the most-changed code file', () => {
const s = snapshotProject(repo);
expect(s).not.toBeNull();
expect(s!.files).toBe(4);
expect(s!.languages[0]).toBe('TypeScript');
expect(s!.hotFile).toEqual({ path: 'src/hot.ts', changes: 3 });
expect(s!.testCommand).toBe('npm test');
expect(firstPrompt(s)).toContain('src/hot.ts');
expect(firstPrompt(s)).toContain('`npm test`');
expect(snapshotLines(s).join('\n')).toContain('Most-changed file (90 days): src/hot.ts (3 commits)');
});
it('returns null outside a git repo, and the prompt still reads well', () => {
const s = snapshotProject(plain);
expect(s).toBeNull();
expect(snapshotLines(s)).toEqual([]);
expect(firstPrompt(s)).toMatch(/review this repo/);
});
it('ignores the npm placeholder test script', () => {
writeFileSync(join(plain, 'package.json'), JSON.stringify({ scripts: { test: 'echo "Error: no test specified" && exit 1' } }));
git(plain, 'init', '-q');
git(plain, 'add', '-A');
git(plain, 'commit', '-q', '-m', 'c');
const s = snapshotProject(plain);
expect(s?.testCommand).toBeUndefined();
expect(s?.hotFile).toBeUndefined();
});
});
+15 -14
View File
@@ -1082,21 +1082,22 @@ const initClaudeAction = async (ctx: CommandContext): Promise<CommandResult> =>
}
}
if (!startDaemon && !startAll) {
if (!startDaemon && !startAll && ctx.flags.format !== 'json') {
// End on something about the user's own repo, not a list of commands
// (adoption plan item 1). Local-only, time-capped, never throws.
const { snapshotProject, snapshotLines, firstPrompt } = await import('../init/first-win.js');
const snap = snapshotProject(ctx.cwd);
const lines = snapshotLines(snap);
if (lines.length) {
output.writeln(output.bold('Your project:'));
output.printList(lines);
output.writeln();
}
output.writeln(output.bold('Try it — open Claude Code here and paste:'));
output.writeln(` ${output.highlight(firstPrompt(snap))}`);
output.writeln();
const bin = (process.argv[1] || '').includes('ruflo') ? 'ruflo' : 'claude-flow';
output.writeln(output.bold('Next steps:'));
output.printList([
`Run ${output.highlight(`${bin} daemon start`)} to start background workers`,
// Memory is initialized automatically during init (persistent by
// default — see executor.ts) — no separate `memory init` step needed
// unless the DB was skipped (MINIMAL_INIT_OPTIONS) or needs --force.
`Run ${output.highlight(`${bin} swarm init`)} to initialize a swarm`,
`Or use ${output.highlight(`${bin} init --start-all`)} to do all of the above`,
options.components.settings ? `Review ${output.highlight('.claude/settings.json')} for hook configurations` : '',
// ADR-150 — surface the new metaharness scorecard to every new user.
// Optional dep; the command degrades gracefully when not installed.
`Run ${output.highlight(`${bin} metaharness score`)} for a 5-dim harness readiness scorecard (ADR-150)`,
].filter(Boolean));
output.writeln(output.dim(`Background workers: ${bin} daemon start · health check: ${bin} doctor`));
}
if (ctx.flags.format === 'json') {
+100
View File
@@ -0,0 +1,100 @@
/**
* The concrete result `ruflo init` ends with (adoption plan item 1): a quick,
* local snapshot of the user's own project, plus one prompt to paste into
* Claude Code. Replaces a list of commands with something about *their* repo.
*
* Local only: `git` with argument arrays (no shell), a hard timeout per call,
* no network. Any failure returns null and init prints nothing extra.
*/
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { extname, join } from 'node:path';
export interface ProjectSnapshot {
files: number;
languages: string[];
hotFile?: { path: string; changes: number };
testCommand?: string;
}
const LANGUAGE: Record<string, string> = {
'.ts': 'TypeScript', '.tsx': 'TypeScript', '.js': 'JavaScript', '.jsx': 'JavaScript', '.mjs': 'JavaScript', '.cjs': 'JavaScript',
'.py': 'Python', '.rs': 'Rust', '.go': 'Go', '.java': 'Java', '.kt': 'Kotlin', '.rb': 'Ruby', '.php': 'PHP',
'.cs': 'C#', '.cpp': 'C++', '.cc': 'C++', '.c': 'C', '.h': 'C', '.swift': 'Swift', '.scala': 'Scala',
'.vue': 'Vue', '.svelte': 'Svelte', '.dart': 'Dart', '.ex': 'Elixir', '.exs': 'Elixir', '.lua': 'Lua',
};
// Files a "riskiest module" suggestion should never point at.
const NOT_CODE = /(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|go\.sum|CHANGELOG[^/]*|README[^/]*|\.github\/|\.claude\/|\.claude-flow\/|dist\/|build\/|node_modules\/)/i;
function git(cwd: string, args: string[], timeoutMs: number): string | null {
const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
return r.status === 0 && typeof r.stdout === 'string' ? r.stdout : null;
}
function testCommandFor(cwd: string): string | undefined {
try {
const pkg = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf8')) as { scripts?: Record<string, string> };
const t = pkg.scripts?.test;
if (t && !/no test specified/i.test(t)) return 'npm test';
} catch { /* not a node project */ }
if (existsSync(join(cwd, 'Cargo.toml'))) return 'cargo test';
if (existsSync(join(cwd, 'go.mod'))) return 'go test ./...';
if (existsSync(join(cwd, 'pyproject.toml')) || existsSync(join(cwd, 'pytest.ini'))) return 'pytest';
return undefined;
}
/** Snapshot of the project at `cwd`, or null when it is not a git repo with code. */
export function snapshotProject(cwd: string, timeoutMs = 2000): ProjectSnapshot | null {
try {
const listed = git(cwd, ['ls-files', '-z'], timeoutMs);
if (!listed) return null;
const files = listed.split('\0').filter(Boolean);
if (files.length === 0) return null;
const counts = new Map<string, number>();
for (const f of files) {
const lang = LANGUAGE[extname(f).toLowerCase()];
if (lang) counts.set(lang, (counts.get(lang) ?? 0) + 1);
}
const languages = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([l]) => l);
// Most-changed code file in the last 90 days (bounded to 500 commits).
let hotFile: ProjectSnapshot['hotFile'];
const log = git(cwd, ['log', '--since=90.days', '--max-count=500', '--name-only', '--pretty=format:'], timeoutMs);
if (log) {
const tracked = new Set(files);
const churn = new Map<string, number>();
for (const line of log.split('\n')) {
const p = line.trim();
if (!p || NOT_CODE.test(p) || !tracked.has(p) || !LANGUAGE[extname(p).toLowerCase()]) continue;
churn.set(p, (churn.get(p) ?? 0) + 1);
}
const top = [...churn.entries()].sort((a, b) => b[1] - a[1])[0];
if (top && top[1] >= 2) hotFile = { path: top[0], changes: top[1] };
}
return { files: files.length, languages, hotFile, testCommand: testCommandFor(cwd) };
} catch {
return null;
}
}
/** The one prompt to paste into Claude Code, specific to this project. */
export function firstPrompt(s: ProjectSnapshot | null): string {
if (s?.hotFile) {
const verify = s.testCommand ? ` and run \`${s.testCommand}\` to prove it` : '';
return `Use a ruflo swarm to review ${s.hotFile.path} (the most-changed file here): find the riskiest logic, add tests for it${verify}, and summarise what you changed.`;
}
return 'Use a ruflo swarm to review this repo: find the riskiest module, write tests for it, and summarise what you changed.';
}
/** Lines for init's closing summary. Empty when there is nothing useful to say. */
export function snapshotLines(s: ProjectSnapshot | null): string[] {
if (!s) return [];
const lines = [`${s.files.toLocaleString('en-US')} tracked file${s.files === 1 ? '' : 's'}${s.languages.length ? ` · ${s.languages.join(', ')}` : ''}`];
if (s.hotFile) lines.push(`Most-changed file (90 days): ${s.hotFile.path} (${s.hotFile.changes} commits)`);
if (s.testCommand) lines.push(`Tests: ${s.testCommand}`);
return lines;
}