Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions src/commands/cli/__tests__/add.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
const mockCliAddInstallOrUpdatePostHogCli = jest.fn();
const mockCliAddInstallSteeringSnippet = jest.fn();
const mockCliAddWizardCapture = jest.fn();
const mockCliAddSetUI = jest.fn();
const mockCliAddUi = {
intro: jest.fn(),
outro: jest.fn(),
log: {
error: jest.fn(),
info: jest.fn(),
success: jest.fn(),
warn: jest.fn(),
},
};

jest.mock('@steps/install-cli-steering', () => ({
CLI_STEERING_TARGETS: [
{
id: 'codex',
name: 'Codex',
instructionsPath: () => '/home/user/.codex/AGENTS.md',
isDetected: () => true,
},
],
detectTargets: jest.fn(),
findTarget: jest.fn(() => ({
id: 'codex',
name: 'Codex',
instructionsPath: () => '/home/user/.codex/AGENTS.md',
isDetected: () => true,
})),
installOrUpdatePostHogCli: mockCliAddInstallOrUpdatePostHogCli,
installSteeringSnippet: mockCliAddInstallSteeringSnippet,
}));
jest.mock('@ui', () => ({
getUI: () => mockCliAddUi,
setUI: mockCliAddSetUI,
}));
jest.mock('@ui/logging-ui', () => ({
LoggingUI: jest.fn(),
}));
jest.mock('@utils/analytics', () => ({
analytics: { wizardCapture: mockCliAddWizardCapture },
}));

import { cliAddCommand } from '../add';

describe('cli add command', () => {
const originalExit = process.exit;

beforeEach(() => {
jest.clearAllMocks();
process.exit = jest.fn() as unknown as typeof process.exit;
mockCliAddInstallOrUpdatePostHogCli.mockReturnValue({ success: true });
mockCliAddInstallSteeringSnippet.mockReturnValue({
success: true,
filePath: '/home/user/.codex/AGENTS.md',
});
});

afterEach(() => {
process.exit = originalExit;
});

async function runHandler() {
cliAddCommand.handler?.({
_: [],
$0: 'wizard',
agent: 'codex',
});
await new Promise((resolve) => setImmediate(resolve));
}

it('installs or updates the CLI before installing steering', async () => {
await runHandler();

expect(mockCliAddInstallOrUpdatePostHogCli).toHaveBeenCalledTimes(1);
expect(mockCliAddInstallSteeringSnippet).toHaveBeenCalledWith(
'/home/user/.codex/AGENTS.md',
);
expect(
mockCliAddInstallOrUpdatePostHogCli.mock.invocationCallOrder[0],
).toBeLessThan(
mockCliAddInstallSteeringSnippet.mock.invocationCallOrder[0],
);
expect(process.exit).toHaveBeenCalledWith(0);
});

it('does not install steering when the CLI install fails', async () => {
mockCliAddInstallOrUpdatePostHogCli.mockReturnValue({
success: false,
error: 'npm failed',
});

await runHandler();

expect(mockCliAddInstallSteeringSnippet).not.toHaveBeenCalled();
expect(mockCliAddUi.log.error).toHaveBeenCalledWith(
'Failed to install or update PostHog CLI: npm failed',
);
expect(process.exit).toHaveBeenCalledWith(1);
});
});
34 changes: 30 additions & 4 deletions src/commands/cli/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@ import {
type CliSteeringTarget,
detectTargets,
findTarget,
installOrUpdatePostHogCli,
installSteeringSnippet,
} from '@steps/install-cli-steering';
import type { Command } from '../command';

export const cliAddCommand: Command = {
name: 'add',
description:
"Add PostHog CLI steering instructions to your coding agent's global instructions file",
"Install or update PostHog CLI and add steering instructions to your coding agent's global instructions file",
options: {
agent: {
describe: 'Agent to install the instructions for',
Expand Down Expand Up @@ -60,13 +61,33 @@ export const cliAddCommand: Command = {
async function runCliAdd(argv: Arguments): Promise<void> {
setUI(new LoggingUI());
const ui = getUI();
ui.intro('PostHog CLI steering instructions');
ui.intro('PostHog CLI setup');

const files = await resolveTargetFiles(argv);
if (files.length === 0) {
process.exit(1);
return;
}

ui.log.info('Installing or updating PostHog CLI...');
const cliInstallResult = installOrUpdatePostHogCli();
if (!cliInstallResult.success) {
ui.log.error(
`Failed to install or update PostHog CLI: ${
cliInstallResult.error ?? ''
}`,
);
analytics.wizardCapture('cli steering installed', {
files: files.length,
failures: files.length,
cli_install_failed: true,
agent: typeof argv.agent === 'string' ? argv.agent : undefined,
});
process.exit(1);
return;
}
ui.log.success('Installed or updated PostHog CLI.');

let failures = 0;
for (const file of files) {
const result = installSteeringSnippet(file);
Expand All @@ -86,9 +107,10 @@ async function runCliAdd(argv: Arguments): Promise<void> {

if (failures > 0) {
process.exit(1);
return;
}
ui.outro(
'Done. Your agent will now use `posthog-cli api` for PostHog tasks.',
'Done. PostHog CLI is installed and your agent will now use `posthog-cli api` for PostHog tasks.',
);
process.exit(0);
}
Expand All @@ -103,7 +125,11 @@ async function resolveTargetFiles(argv: Arguments): Promise<string[]> {

if (typeof argv.agent === 'string') {
// yargs `choices` already rejected unknown ids.
const target = findTarget(argv.agent)!;
const target = findTarget(argv.agent);
if (!target) {
ui.log.error(`Unsupported agent: ${argv.agent}`);
return [];
}
return [target.instructionsPath()];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
CLI_STEERING_TARGETS,
detectTargets,
findTarget,
installOrUpdatePostHogCli,
installSteeringSnippet,
} from '@steps/install-cli-steering';

Expand Down Expand Up @@ -55,8 +56,45 @@ describe('install-cli-steering', () => {
});
});

describe('installOrUpdatePostHogCli', () => {
it('installs or updates the latest published CLI globally', () => {
spawnSyncMock.mockReturnValue({ status: 0, stdout: '', stderr: '' });

const result = installOrUpdatePostHogCli();

expect(result).toEqual({ success: true });
const [command, args, options] = spawnSyncMock.mock.calls[0];
expect(command).toBe('npm');
expect(args).toEqual(['install', '--global', '@posthog/cli@latest']);
expect(options.encoding).toBe('utf-8');
});

it('surfaces stderr when npm exits non-zero', () => {
spawnSyncMock.mockReturnValue({
status: 1,
stdout: '',
stderr: 'Error: install failed\n',
});

const result = installOrUpdatePostHogCli();
expect(result.success).toBe(false);
expect(result.error).toContain('install failed');
});

it('explains when npm itself cannot be run', () => {
spawnSyncMock.mockReturnValue({
error: new Error('spawn npm ENOENT'),
status: null,
});

const result = installOrUpdatePostHogCli();
expect(result.success).toBe(false);
expect(result.error).toContain('Is Node.js installed?');
});
});

describe('installSteeringSnippet', () => {
it('delegates to the latest published CLI with the experimental env set', () => {
it('delegates to the installed CLI with the experimental env set', () => {
spawnSyncMock.mockReturnValue({ status: 0, stdout: '', stderr: '' });

const result = installSteeringSnippet('/home/user/.claude/CLAUDE.md');
Expand All @@ -66,10 +104,8 @@ describe('install-cli-steering', () => {
filePath: '/home/user/.claude/CLAUDE.md',
});
const [command, args, options] = spawnSyncMock.mock.calls[0];
expect(command).toBe('npx');
expect(command).toBe('posthog-cli');
expect(args).toEqual([
'-y',
'@posthog/cli@latest',
'api',
'agents-md',
'install',
Expand All @@ -91,15 +127,16 @@ describe('install-cli-steering', () => {
expect(result.error).toContain('something broke');
});

it('explains when npx itself cannot be run', () => {
it('explains when posthog-cli itself cannot be run', () => {
spawnSyncMock.mockReturnValue({
error: new Error('spawn npx ENOENT'),
error: new Error('spawn posthog-cli ENOENT'),
status: null,
});

const result = installSteeringSnippet('/tmp/AGENTS.md');
expect(result.success).toBe(false);
expect(result.error).toContain('Is Node.js installed?');
expect(result.error).toContain('posthog-cli');
expect(result.error).toContain('PATH');
});
});
});
76 changes: 55 additions & 21 deletions src/steps/install-cli-steering/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,47 +63,81 @@ export interface SteeringInstallResult {
error?: string;
}

export interface CliInstallResult {
success: boolean;
error?: string;
}

const spawnOptions = {
encoding: 'utf-8' as const,
// npm/posthog-cli are npm.cmd/posthog-cli.cmd on Windows; spawnSync only
// resolves them through a shell.
shell: process.platform === 'win32',
};

/**
* Install or update the PostHog CLI in the user's environment. `npm install
* --global @posthog/cli@latest` covers both first-time installs and upgrades
* for existing npm-installed CLIs.
*/
export function installOrUpdatePostHogCli(): CliInstallResult {
const args = ['install', '--global', '@posthog/cli@latest'];
debug(`Running npm ${args.join(' ')}`);

const result = spawnSync('npm', args, spawnOptions);

if (result.error) {
return {
success: false,
error: `Failed to run npm: ${result.error.message}. Is Node.js installed?`,
};
}
if (result.status !== 0) {
const detail = (result.stderr || result.stdout || '').trim();
return {
success: false,
error:
detail ||
`npm install --global @posthog/cli@latest exited with status ${
result.status ?? 'unknown'
}`,
};
}
return { success: true };
}

/**
* Delegate the actual write to `posthog-cli api agents-md install`, pinned to
* `@posthog/cli@latest` via npx. The steering snippet lives in the CLI (its
* single source of truth), so going through the latest release means a rerun
* always refreshes the installed `<posthog>` block to the current content
* instead of baking a copy into the wizard that would go stale.
* Delegate the actual write to the installed `posthog-cli api agents-md
* install`. The steering snippet lives in the CLI (its single source of truth),
* so the command should run only after `installOrUpdatePostHogCli` refreshes
* the CLI to the latest release.
*/
export function installSteeringSnippet(
filePath: string,
): SteeringInstallResult {
const args = [
'-y',
'@posthog/cli@latest',
'api',
'agents-md',
'install',
'--path',
filePath,
];
debug(`Running npx ${args.join(' ')}`);
const args = ['api', 'agents-md', 'install', '--path', filePath];
debug(`Running posthog-cli ${args.join(' ')}`);

const result = spawnSync('npx', args, {
encoding: 'utf-8',
const result = spawnSync('posthog-cli', args, {
...spawnOptions,
env: { ...process.env, POSTHOG_CLI_EXPERIMENTAL_API: '1' },
// npx is npx.cmd on Windows; spawnSync only resolves it through a shell.
shell: process.platform === 'win32',
});

if (result.error) {
return {
success: false,
filePath,
error: `Failed to run npx: ${result.error.message}. Is Node.js installed?`,
error: `Failed to run posthog-cli: ${result.error.message}. Make sure npm's global bin directory is on your PATH.`,
};
}
if (result.status !== 0) {
const detail = (result.stderr || result.stdout || '').trim();
return {
success: false,
filePath,
error: detail || `npx exited with status ${result.status ?? 'unknown'}`,
error:
detail ||
`posthog-cli exited with status ${result.status ?? 'unknown'}`,
};
}
return { success: true, filePath };
Expand Down
Loading