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
33 changes: 27 additions & 6 deletions bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import { hideBin } from 'yargs/helpers';
import { VERSION } from './src/lib/version.js';

const WIZARD_VERSION = VERSION;

Check warning on line 9 in bin.ts

View workflow job for this annotation

GitHub Actions / Lint

Unsafe assignment of an `any` value

const NODE_VERSION_RANGE = '>=18.17.0';

Expand Down Expand Up @@ -279,7 +279,7 @@
const { startPlayground } = await import(
'./src/ui/tui/playground/start-playground.js'
);
(startPlayground as (version: string) => void)(WIZARD_VERSION);

Check warning on line 282 in bin.ts

View workflow job for this annotation

GitHub Actions / Lint

Unsafe argument of type `any` assigned to a parameter of type `string`
})();
} else if (options.skill) {
// Run a specific skill by ID
Expand All @@ -300,7 +300,7 @@
spinnerMessage: `Running ${skillId}...`,
estimatedDurationMinutes: 5,
});
runWizard(config, options);
runWizard(config, { ...options, skillId });
})();
} else {
// Interactive TTY: run core-integration through the unified workflow path.
Expand Down Expand Up @@ -359,7 +359,7 @@
);

const { Flow } = await import('./src/ui/tui/router.js');
const tui = startTUI(WIZARD_VERSION, Flow.McpAdd);

Check warning on line 362 in bin.ts

View workflow job for this annotation

GitHub Actions / Lint

Unsafe argument of type `any` assigned to a parameter of type `string`
const session = buildSession({
debug: options.debug,
localMcp: options.local,
Expand Down Expand Up @@ -405,7 +405,7 @@
);

const { Flow } = await import('./src/ui/tui/router.js');
const tui = startTUI(WIZARD_VERSION, Flow.McpRemove);

Check warning on line 408 in bin.ts

View workflow job for this annotation

GitHub Actions / Lint

Unsafe argument of type `any` assigned to a parameter of type `string`
const session = buildSession({
debug: options.debug,
localMcp: options.local,
Expand All @@ -431,7 +431,7 @@
// ── Skill-based workflow subcommands (derived from registry) ─────────
for (const wfConfig of getSubcommandWorkflows()) {
cli.command(
wfConfig.command!,

Check warning on line 434 in bin.ts

View workflow job for this annotation

GitHub Actions / Lint

Forbidden non-null assertion
wfConfig.description,
(y) => y.options(skillSubcommandOptions),
(argv) => {
Expand Down Expand Up @@ -467,9 +467,16 @@

const { startTUI } = await import('./src/ui/tui/start-tui.js');
const { buildSession } = await import('./src/lib/wizard-session.js');
const { TaskStreamPush } = await import('./src/lib/task-stream/index.js');
const { FileDestination } = await import(
'./src/lib/task-stream/destinations/file.js'
);
const { PostHogDestination } = await import(
'./src/lib/task-stream/destinations/posthog.js'
);
const { analytics } = await import('./src/utils/analytics.js');

// flowKey values match Flow enum values by convention
const tui = startTUI(WIZARD_VERSION, config.flowKey as any);

Check warning on line 479 in bin.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type

Check warning on line 479 in bin.ts

View workflow job for this annotation

GitHub Actions / Lint

Unsafe argument of type `any` assigned to a parameter of type `Flow`

Check warning on line 479 in bin.ts

View workflow job for this annotation

GitHub Actions / Lint

Unsafe argument of type `any` assigned to a parameter of type `string`

const session = buildSession({
debug: options.debug as boolean | undefined,
Expand All @@ -482,17 +489,25 @@
projectId: options.projectId as string | undefined,
email: options.email as string | undefined,
menu: options.menu as boolean | undefined,
integration: options.integration as any,

Check warning on line 492 in bin.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type

Check warning on line 492 in bin.ts

View workflow job for this annotation

GitHub Actions / Lint

Unsafe assignment of an `any` value
benchmark: options.benchmark as boolean | undefined,
yaraReport: options.yaraReport as boolean | undefined,
});
// Set workflow metadata for TUI display
session.workflowLabel = config.flowKey;
const runDef = typeof config.run === 'object' ? config.run : null;
session.skillId = runDef?.skillId ?? null;
if (options.skillId) {
session.skillId = options.skillId as string;
}

tui.store.session = session;

// Task stream — pushes state to external consumers on task changes
const taskStream = new TaskStreamPush({
store: tui.store,
workflowId: config.flowKey,
destinations: [new FileDestination(), new PostHogDestination()],
});
tui.store.onTasksChanged = () => void taskStream.push();

await tui.store.runReadyHooks();
await tui.store.getGate('intro');

Expand Down Expand Up @@ -537,6 +552,13 @@
resolve();
}
});

try {
await taskStream.dispose();
} catch (error) {
analytics.captureException(error as Error);
}
tui.unmount();
process.exit(0);
} catch (err) {
if (runtimeEnv('DEBUG') || runtimeEnv('POSTHOG_WIZARD_DEBUG')) {
Expand Down Expand Up @@ -613,7 +635,6 @@
});
session.workflowLabel = config.flowKey;
const runDef = typeof config.run === 'object' ? config.run : null;
session.skillId = runDef?.skillId ?? null;

getUI().intro('Welcome to the PostHog setup wizard');
getUI().log.info(`Running ${config.flowKey} in CI mode`);
Expand Down
1 change: 1 addition & 0 deletions src/lib/agent/agent-runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ export async function runWorkflow(
): Promise<void> {
// 1. Init logging + debug
initLogFile();
session.skillId = config.skillId ?? config.integrationLabel;
logToFile(`[agent-runner] START ${config.integrationLabel}`);

if (session.debug) {
Expand Down
5 changes: 3 additions & 2 deletions src/lib/middleware/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import path from 'path';
import { logToFile } from '../../utils/debug';
import { AgentSignals } from '../agent/agent-interface';
import { runtimeEnv } from '@env';
import { WIZARD_BENCHMARK_FILE, WIZARD_LOG_FILE } from '../../utils/paths';

export interface BenchmarkConfig {
/** Enable/disable individual metric plugins */
Expand Down Expand Up @@ -41,9 +42,9 @@ const DEFAULT_CONFIG: BenchmarkConfig = {
jsonWriter: true,
},
output: {
benchmarkPath: '/tmp/posthog-wizard-benchmark.json',
benchmarkPath: WIZARD_BENCHMARK_FILE,
benchmarkEnabled: true,
logPath: '/tmp/posthog-wizard.log',
logPath: WIZARD_LOG_FILE,
logEnabled: true,
suppressWizardLogs: false,
},
Expand Down
259 changes: 259 additions & 0 deletions src/lib/task-stream/__tests__/task-stream-push.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,259 @@
import { TaskStreamPush } from '../task-stream-push';
import { StreamEvent } from '../types';
import type { TaskStreamDestination, TaskStreamUpdate } from '../types';
import type { WizardStore, TaskItem } from '../../../ui/tui/store';
import { RunPhase } from '../../wizard-session';

// Mocks and stuff

type Listener = () => void;

function createMockStore(overrides: Partial<MockStoreState> = {}) {
const listeners: Listener[] = [];
const state: MockStoreState = {
runPhase: RunPhase.Idle,
skillId: 'test-skill',
tasks: [],
eventPlan: [],
...overrides,
};

const store = {
get session() {
return { runPhase: state.runPhase, skillId: state.skillId };
},
get tasks() {
return state.tasks;
},
get eventPlan() {
return state.eventPlan;
},
subscribe(cb: Listener) {
listeners.push(cb);
return () => {
const i = listeners.indexOf(cb);
if (i >= 0) listeners.splice(i, 1);
};
},
// mock setter and getter
_emit() {
for (const cb of listeners) cb();
},
_set(patch: Partial<MockStoreState>) {
Object.assign(state, patch);
},
_listenerCount() {
return listeners.length;
},
};

return store as typeof store & WizardStore;
}

interface MockStoreState {
runPhase: RunPhase;
skillId: string | null;
tasks: TaskItem[];
eventPlan: unknown[];
}

function createMockDestination(
name = 'test',
): TaskStreamDestination & { calls: Array<[StreamEvent, TaskStreamUpdate]> } {
const calls: Array<[StreamEvent, TaskStreamUpdate]> = [];
return {
name,
calls,
send: jest.fn((event: StreamEvent, payload: TaskStreamUpdate) => {
calls.push([event, payload]);
return Promise.resolve();
}),
};
}

function createPush(
store: ReturnType<typeof createMockStore>,
dest?: ReturnType<typeof createMockDestination>,
) {
const d = dest ?? createMockDestination();
const push = new TaskStreamPush({
store,
workflowId: 'test-workflow',
destinations: [d],
});
return { push, dest: d };
}

describe('TaskStreamPush', () => {
describe('Coorect order of events', () => {
it('first push sends CREATE', async () => {
const store = createMockStore();
const { push, dest } = createPush(store);

await push.push();

expect(dest.calls).toHaveLength(1);
expect(dest.calls[0][0]).toBe(StreamEvent.Create);
});

it('subsequent pushes send UPDATE', async () => {
const store = createMockStore();
const { push, dest } = createPush(store);

await push.push();
await push.push();
await push.push();

expect(dest.calls.map(([ev]) => ev)).toEqual([
StreamEvent.Create,
StreamEvent.Update,
StreamEvent.Update,
]);
});

it('sends COMPLETE when runPhase is completed', async () => {
const store = createMockStore();
const { push, dest } = createPush(store);

await push.push(); // CREATE
store._set({ runPhase: RunPhase.Completed });
await push.push();

expect(dest.calls.map(([ev]) => ev)).toEqual([
StreamEvent.Create,
StreamEvent.Complete,
]);
});

it('sends ERROR when runPhase is error', async () => {
const store = createMockStore();
const { push, dest } = createPush(store);

await push.push(); // CREATE
store._set({ runPhase: RunPhase.Error });
await push.push();

expect(dest.calls[1][0]).toBe(StreamEvent.Error);
});

it('first push with terminal phase sends CREATE then COMPLETE on next', async () => {
const store = createMockStore({ runPhase: RunPhase.Completed });
const { push, dest } = createPush(store);

await push.push();
await push.push();

expect(dest.calls.map(([ev]) => ev)).toEqual([
StreamEvent.Create,
StreamEvent.Complete,
]);
});
});

describe('payload contents', () => {
it('session_id is correctly formed', async () => {
const store = createMockStore();
const { push, dest } = createPush(store);

await push.push();

const payload = dest.calls[0][1];
expect(payload.workflow_id).toBe('test-workflow');
expect(payload.skill_id).toBe('test-skill');
expect(payload.session_id).toContain('test-workflow-test-skill-');
});

it('includes eventPlan when non-empty', async () => {
const plan = [{ name: 'signup', description: 'User signs up' }];
const store = createMockStore({ eventPlan: plan });
const { push, dest } = createPush(store);

await push.push();

expect(dest.calls[0][1].event_plan).toEqual(plan);
});

it('omits eventPlan when empty', async () => {
const store = createMockStore({ eventPlan: [] });
const { push, dest } = createPush(store);

await push.push();

expect(dest.calls[0][1].event_plan).toBeUndefined();
});
});

describe('destinations are independent', () => {
it('one destination failing does not break others', async () => {
const store = createMockStore();
const good = createMockDestination('good');
const bad: TaskStreamDestination = {
name: 'bad',
send: jest.fn(() => {
return Promise.reject(new Error('network down'));
}),
};
const push = new TaskStreamPush({
store,
workflowId: 'w',
destinations: [bad, good],
});

// This should still happily complete and not block the wizard
await push.push();

expect(bad.send).toHaveBeenCalledTimes(1);
expect(good.calls).toHaveLength(1);
});

it('push resolves even when all destinations fail', async () => {
const store = createMockStore();
const bad: TaskStreamDestination = {
name: 'bad',
send: jest.fn(() => {
return Promise.reject(new Error('fail'));
}),
};
const push = new TaskStreamPush({
store,
workflowId: 'w',
destinations: [bad],
});

await expect(push.push()).resolves.toBeUndefined();
});
});

describe('dispose', () => {
it('sends a final push', async () => {
const store = createMockStore();
const { push, dest } = createPush(store);

await push.dispose();

expect(dest.calls).toHaveLength(1);
});

it('sends COMPLETE when runPhase is completed at dispose time', async () => {
const store = createMockStore();
const { push, dest } = createPush(store);

await push.push();
store._set({ runPhase: RunPhase.Completed });
await push.dispose();

expect(dest.calls[1][0]).toBe(StreamEvent.Complete);
});

it('sends ERROR when runPhase is error at dispose time', async () => {
const store = createMockStore();
const { push, dest } = createPush(store);

await push.push();
store._set({ runPhase: RunPhase.Error });
await push.dispose();

expect(dest.calls[1][0]).toBe(StreamEvent.Error);
});
});
});
23 changes: 23 additions & 0 deletions src/lib/task-stream/destinations/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { appendFileSync } from 'node:fs';
import type {
TaskStreamDestination,
TaskStreamUpdate,
StreamEvent,
} from '../types';
import { WIZARD_TASK_STREAM_LOG } from '../../../utils/paths';

export class FileDestination implements TaskStreamDestination {
readonly name = 'file';

send(event: StreamEvent, payload: TaskStreamUpdate): Promise<void> {
try {
appendFileSync(
WIZARD_TASK_STREAM_LOG,
`[${event}] ${JSON.stringify(payload, null, 2)}\n`,
);
} catch {
// Non-critical
}
return Promise.resolve();
}
}
14 changes: 14 additions & 0 deletions src/lib/task-stream/destinations/posthog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type {
TaskStreamDestination,
TaskStreamUpdate,
StreamEvent,
} from '../types';

export class PostHogDestination implements TaskStreamDestination {
readonly name = 'posthog';

send(_event: StreamEvent, _payload: TaskStreamUpdate): Promise<void> {
// TODO: implement when the PostHog API surface is defined.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wire this up to send to where ever in the heavens (posthog app)

return Promise.resolve();
}
}
Loading
Loading