Skip to content

Implement the setup wizard engine that sequences checks and safe actions #1601

Closed

Description

@propr-dev

Context

The setup wizard must combine check and init stack behavior, then guide the user through Docker, images, agent selection, GitHub auth, intake mode, stack startup, whitelist, optional repo addition, and UI access. The engine should be UI-agnostic so it works with Ink and with the fallback sequential wizard.

Requirements

  • Add a setup runner that executes the setup steps in a safe order.
  • Run environment checks first and use their results to decide which steps need action.
  • Initialize stack only when .env is missing or the user chooses a new root.
  • Pull only core images by default and agent images only for selected agents.
  • Start stack and validate backend health after startup.
  • Never delete user data or overwrite existing .env wholesale.

Implementation Specification

Create packages/cli/src/commands/setup/engine.ts. The first version can expose callback hooks for prompts and progress; Ink and fallback renderers will provide those callbacks in later issues.

Acceptance Criteria

  • The engine can run in tests with mocked prompt callbacks.
  • Existing functional stack installs are left intact when setup is re-run.
  • Setup can skip optional repo addition without failing the entire command.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Jun 22, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    The engine is implemented as a stateful async workflow with injected prompt callbacks. This separates decisions from rendering and makes the fallback path reuse the same behavior. We run checks before mutation because it gives the wizard a clear map of what is already configured. We initialize the stack before GitHub intake writes because intake choices need a real .env target. Agent image pulling is selective to avoid downloading images for agents the operator will not use.

    File: packages/cli/src/commands/setup/engine.ts (new file)

    Why this file: This file owns the orchestration of setup steps. It connects existing commands and APIs while staying independent from Ink/readline presentation.

    import { spawnSync } from 'node:child_process';
    import { existsSync } from 'node:fs';
    import { join } from 'node:path';
    import { createApiClientWithConfig } from '../../api/client.js';
    import { addRepo } from '../../api/repos.js';
    import { updateSettings } from '../../api/settings.js';
    import { createConfigManager } from '../../config/index.js';
    import { getHostConfig } from '../../orchestrator/index.js';
    import { scaffoldStack } from '../initStack.js';
    import { runChecks } from '../checkCommands.js';
    import { writeSetupEnv, stackEnvExists, updateStep } from './state.js';
    import type { SetupDecision, SetupRunOptions, SetupWizardState } from './types.js';
    
    export interface SetupPrompts {
      confirm(message: string, defaultValue?: boolean): Promise<boolean>;
      input(message: string, defaultValue?: string): Promise<string>;
      choose<T extends string>(message: string, choices: Array<SetupDecision<T>>, defaultValue: T): Promise<T>;
      multiChoose<T extends string>(message: string, choices: Array<SetupDecision<T>>, defaults: T[]): Promise<T[]>;
    }
    
    export interface SetupEngineHooks {
      onState?(state: SetupWizardState): void;
      onMessage?(message: string): void;
    }
    
    const AGENT_IMAGE_KEYS = {
      claude: 'agent-claude',
      codex: 'agent-codex',
      antigravity: 'agent-antigravity',
      opencode: 'agent-opencode',
      vibe: 'agent-vibe',
    } as const;
    
    type AgentType = keyof typeof AGENT_IMAGE_KEYS;
    
    const AGENT_CHOICES: Array<SetupDecision<AgentType>> = [
      { value: 'claude', label: 'Claude', detail: 'Anthropic Claude Code agent image and credentials.' },
      { value: 'codex', label: 'Codex', detail: 'OpenAI Codex agent image and credentials.' },
      { value: 'antigravity', label: 'Antigravity', detail: 'Antigravity agent image using Gemini credential storage.' },
      { value: 'opencode', label: 'OpenCode', detail: 'OpenCode image plus XDG config and data directories.' },
      { value: 'vibe', label: 'Mistral Vibe', detail: 'Vibe image using ~/.vibe or MISTRAL_API_KEY.' },
    ];
    
    export async function runSetupEngine(
      state: SetupWizardState,
      options: SetupRunOptions,
      prompts: SetupPrompts,
      hooks: SetupEngineHooks = {}
    ): Promise<SetupWizardState> {
      let nextState = state;
      const emit = (patchState: SetupWizardState): void => {
        nextState = patchState;
        hooks.onState?.(nextState);
      };
    
      emit(updateStep(nextState, 'environment', { status: 'running', detail: 'Running ProPR environment checks.' }));
      const initialChecks = await runChecks({ root: options.root, skipRemoteImageCheck: options.skipRemoteImageCheck });
      emit(updateStep(nextState, 'environment', {
        status: initialChecks.anyFail ? 'warning' : 'complete',
        detail: initialChecks.anyFail ? 'Checks found issues that setup can guide you through.' : 'Environment checks completed.',
        checks: initialChecks.results,
      }));
    
      const configManager = await createConfigManager();
      const rootDir = nextState.rootDir;
    
      emit(updateStep(nextState, 'docker', { status: 'running', detail: 'Checking Docker daemon access.' }));
      const { orch, cfg } = await getHostConfig({ configManager, root: rootDir });
      if (!orch.dockerAvailable()) {
        emit(updateStep(nextState, 'docker', { status: 'blocked', detail: 'Docker is not reachable. Start Docker, then rerun setup.' }));
        return nextState;
      }
      emit(updateStep(nextState, 'docker', { status: 'complete', detail: 'Docker daemon is reachable.' }));
    
      emit(updateStep(nextState, 'stack-init', { status: 'running', detail: 'Checking stack root.' }));
      if (!stackEnvExists(rootDir)) {
        const shouldInit = await prompts.confirm(`Initialize ProPR stack in ${rootDir}?`, true);
        if (!shouldInit) {
          emit(updateStep(nextState, 'stack-init', { status: 'blocked', detail: 'Stack initialization is required before setup can continue.' }));
          return nextState;
        }
        // Use force=false so setup never overwrites an operator-managed .env during
        // a re-run. If a file appears concurrently, scaffoldStack will preserve it.
        await scaffoldStack({ rootDir, force: false, configManager });
        emit(updateStep(nextState, 'stack-init', { status: 'complete', detail: `Initialized stack root at ${rootDir}.` }));
      } else {
        emit(updateStep(nextState, 'stack-init', { status: 'complete', detail: 'Existing stack root detected; preserving current configuration.' }));
      }
    
      emit(updateStep(nextState, 'images', { status: 'running', detail: 'Selecting container images to pull.' }));
      const selectedAgents = await prompts.multiChoose('Which coding agents should setup enable?', AGENT_CHOICES, []);
      const imageKeys = new Set(['app', 'ui', 'redis', ...selectedAgents.map((agent) => AGENT_IMAGE_KEYS[agent])]);
      for (const [key, tag] of Object.entries(cfg.images)) {
        if (!imageKeys.has(key)) continue;
        hooks.onMessage?.(`Pulling ${tag}`);
        const pulled = orch.docker(['pull', tag], { capture: true });
        if (pulled.status !== 0) {
          emit(updateStep(nextState, 'images', { status: 'warning', detail: `Could not pull ${tag}: ${(pulled.stderr || pulled.stdout).trim()}` }));
          return nextState;
        }
        // Tag agent images as latest because existing agent defaults point at
        // propr/agent-*:latest. This keeps setup-compatible images aligned with
        // the manifest version while preserving current config conventions.
        orch.tagAgentLatest(key, tag);
      }
      emit(updateStep(nextState, 'images', { status: 'complete', detail: 'Required images are available locally.' }));
    
      emit(updateStep(nextState, 'github-cli', { status: 'running', detail: 'Checking GitHub CLI session.' }));
      if (spawnSync('gh', ['--version'], { stdio: 'ignore' }).status !== 0) {
        emit(updateStep(nextState, 'github-cli', { status: 'warning', detail: 'GitHub CLI is not installed. Install gh or pass a token later with propr login.' }));
      } else if (spawnSync('gh', ['auth', 'status'], { stdio: 'ignore' }).status !== 0) {
        const loginNow = await prompts.confirm('No active gh session found. Run gh auth login now?', true);
        if (loginNow) spawnSync('gh', ['auth', 'login', '-s', 'repo,read:org'], { stdio: 'inherit' });
        emit(updateStep(nextState, 'github-cli', { status: 'complete', detail: 'GitHub CLI authentication step finished.' }));
      } else {
        emit(updateStep(nextState, 'github-cli', { status: 'complete', detail: 'Existing gh session detected.' }));
      }
    
      emit(updateStep(nextState, 'github-intake', { status: 'running', detail: 'Choosing GitHub event ingestion mode.' }));
      const intake = await prompts.choose('Choose GitHub event ingestion mode.', [
        { value: 'app', label: 'ProPR App', detail: 'Recommended shared-app/relay path; simplest setup and supports managed event handling.' },
        { value: 'polling', label: 'Polling', detail: 'Private deployment default; no public webhook endpoint required, checks GitHub periodically.' },
        { value: 'webhooks', label: 'Direct webhooks', detail: 'Lowest latency, but requires public HTTPS endpoint and webhook secret.' },
      ], 'app');
      if (intake === 'polling') writeSetupEnv(rootDir, { ENABLE_GITHUB_WEBHOOKS: 'false' });
      if (intake === 'webhooks') {
        const secret = await prompts.input('Webhook secret', '');
        writeSetupEnv(rootDir, { ENABLE_GITHUB_WEBHOOKS: 'true', GH_WEBHOOK_SECRET: secret });
      }
      emit(updateStep(nextState, 'github-intake', { status: 'complete', detail: `Selected ${intake}. Docs: https://docs.propr.dev/operations/github-auth` }));
    
      emit(updateStep(nextState, 'stack-start', { status: 'running', detail: 'Starting ProPR stack.' }));
      orch.ensureNetwork(cfg);
      orch.startStack(cfg, { ui: true, docs: false, onLog: hooks.onMessage });
      const client = createApiClientWithConfig(configManager, { baseUrl: cfg.apiPublicUrl });
      const status = await client.get('/api/status', { timeout: 30_000 });
      emit(updateStep(nextState, 'stack-start', { status: 'complete', detail: `Backend responded with HTTP ${status.status}.` }));
    
      emit(updateStep(nextState, 'whitelist', { status: 'running', detail: 'Configuring GitHub user whitelist.' }));
      const currentUser = spawnSync('gh', ['api', 'user', '--jq', '.login'], { encoding: 'utf8' }).stdout.trim();
      const whitelist = await prompts.input('Comma-separated GitHub usernames allowed to trigger work', currentUser);
      if (whitelist.trim()) await updateSettings({ github_user_whitelist: whitelist.split(',').map((name) => name.trim()).filter(Boolean) }, client);
      emit(updateStep(nextState, 'whitelist', { status: whitelist.trim() ? 'complete' : 'warning', detail: whitelist.trim() ? 'Whitelist saved.' : 'Whitelist skipped; configure it before production use.' }));
    
      emit(updateStep(nextState, 'repository', { status: 'running', detail: 'Optional repository setup.' }));
      const repo = await prompts.input('Repository to monitor (owner/repo), or leave blank to skip', '');
      if (repo.trim()) await addRepo(repo.trim(), {}, client);
      emit(updateStep(nextState, 'repository', { status: repo.trim() ? 'complete' : 'skipped', detail: repo.trim() ? `Added ${repo.trim()}.` : 'Repository setup skipped.' }));
    
      emit(updateStep(nextState, 'web-ui', { status: 'complete', detail: `Open ${cfg.frontendUrl}. Review security hardening: https://docs.propr.dev/tutorials/setup-vps-hardening` }));
      return nextState;
    }
  2. propr-dev commented on Jun 22, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-4-8 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: claude
    • Model: claude-opus-4-8
    • Branch: 1601/claude-opus-4-8-implement-the-setup-wizar-20260622-0950-0em
    • Base Branch: 1599-epic-build-comprehensive-b5c
    • Worktree: issue-1601-20260622-0950-claude-opus-4-8-0em

    🔍 Track Task Execution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions