/** * `mod8 connect` subcommand group. * * mod8 connect — onboard a new product * mod8 connect list — list connected products * mod8 connect remove — delete product config (does not touch repo) * mod8 connect add-adapter * — store adapter creds (interactive prompt) * * The onboarding wizard scaffolds product.md.tmpl + a starter * policy.yaml inheriting from _defaults. Phase 4: shows which * adapters are available + how to enable each. */ import chalk from 'chalk'; import { promises as fs } from 'node:fs'; import { existsSync } from 'node:fs'; import { createInterface } from 'node:readline'; import { dirname } from 'node:path'; import { productDirFor, productFiles, PRODUCTS_ROOT, validateProductSlug, buildProductContext, connectorPath, RESERVED_PRODUCT_SLUGS } from '../memory/paths.js'; import { list as listAdapters } from '../loop/adapters/registry.js'; const STARTER_POLICY = `# Auto-generated by \`mod8 connect \` — edit before running the loop. schemaVersion: 1 inherit_from: _defaults # Autonomy — start at L1 (suggest-only) and raise as you trust the loop. autonomy: 1 # Budget caps (USD) — override _defaults here. budget: monthly_usd: 25 per_tick_usd: 0.25 per_phase_usd: 0.10 per_proposal_usd: 2 per_campaign_usd: 0 # Repos this product owns. repos: allowed: [] # e.g. ["github.com/your-org/your-repo"] branches: protected: [main, master, release/*] auto_pr_allowed: false auto_merge_allowed: false files: protected: # changes require explicit approval - LICENSE - package.json:version off_limits: # never proposed - .env* - "**/*.pem" - "**/secrets/*" # Test command — used by the build phase to validate patches. tests: cmd: "npm test" # Cadence (minutes / hours). cadence: sense_every_minutes: 60 ideate_every_hours: 6 measure_wait_hours: 168 concurrent_worktrees: 3 `; const STARTER_DEFAULTS = `# _defaults — shared baseline policy that other products' policies # can inherit_from. Anything here is overridden by the per-product # policy.yaml. Edit to set company-wide guardrails. schemaVersion: 1 autonomy: 1 budget: monthly_usd: 50 per_tick_usd: 0.50 per_phase_usd: 0.15 per_proposal_usd: 5 per_campaign_usd: 0 repos: allowed: [] branches: protected: [main, master] auto_pr_allowed: false auto_merge_allowed: false files: protected: - LICENSE off_limits: - .env* - "**/*.pem" - "**/secrets/*" tests: cmd: "true" cadence: sense_every_minutes: 60 ideate_every_hours: 6 measure_wait_hours: 168 concurrent_worktrees: 3 voice: banned_phrases: - revolutionary - best-in-class - synergies legal_claims: forbidden pricing_claims: approval-required `; export async function connectAddProduct(slug: string): Promise { try { validateProductSlug(slug); } catch (err) { process.stderr.write(chalk.red(`mod8 connect: ${err instanceof Error ? err.message : String(err)}\n`)); process.exit(1); } // Ensure _defaults exists so inherit_from resolves. const defaultsDir = `${PRODUCTS_ROOT}/_defaults`; if (!existsSync(`${defaultsDir}/policy.yaml`)) { await fs.mkdir(defaultsDir, { recursive: true, mode: 0o700 }); await fs.writeFile(`${defaultsDir}/policy.yaml`, STARTER_DEFAULTS, { mode: 0o600 }); process.stdout.write(chalk.dim(` scaffolded ${defaultsDir}/policy.yaml (org-wide defaults)\n`)); } const productDir = productDirFor(slug); await fs.mkdir(productDir, { recursive: true, mode: 0o700 }); const ctx = buildProductContext(slug, process.cwd(), 0); const policyPath = productFiles.policyYaml(ctx); if (existsSync(policyPath)) { process.stderr.write(chalk.yellow(`mod8 connect: ${slug} already exists at ${productDir}\n`) + chalk.dim(` edit policy.yaml directly, or remove first: mod8 connect remove ${slug}\n`)); process.exit(1); } await fs.writeFile(policyPath, STARTER_POLICY, { mode: 0o600 }); // Scaffold product.md.tmpl so the user has a charter to fill in. const { read } = await import('../memory/product.js'); try { await read(ctx); } catch { /* expected — generates .tmpl */ } process.stdout.write( chalk.green(`✓ connected product "${slug}"\n`) + chalk.dim(` ${productDir}\n\n`) + chalk.bold('next steps:\n') + ` 1. Edit ${productFiles.productMd(ctx)}.tmpl and rename to product.md (the loop refuses to run without it).\n` + ` 2. Edit ${policyPath} — set autonomy, allowed repos, file protections.\n` + ` 3. Add adapter credentials: mod8 connect add-adapter ${slug} \n` + ` 4. Run a tick: mod8 loop tick --slug ${slug}\n` ); } export async function connectList(): Promise { if (!existsSync(PRODUCTS_ROOT)) { process.stdout.write(chalk.dim('no products connected — try `mod8 connect `.\n')); return; } const entries = await fs.readdir(PRODUCTS_ROOT, { withFileTypes: true }); const slugs = entries .filter((e) => e.isDirectory() && !RESERVED_PRODUCT_SLUGS.includes(e.name)) .map((e) => e.name) .sort(); if (slugs.length === 0) { process.stdout.write(chalk.dim('no products connected — try `mod8 connect `.\n')); return; } process.stdout.write(chalk.bold(`connected products (${slugs.length}):\n`)); for (const slug of slugs) { const ctx = buildProductContext(slug, process.cwd(), 0); const hasPolicy = existsSync(productFiles.policyYaml(ctx)); const hasProductMd = existsSync(productFiles.productMd(ctx)); process.stdout.write(` · ${chalk.bold(slug)} ${hasPolicy ? chalk.green('policy ✓') : chalk.yellow('policy missing')} ${hasProductMd ? chalk.green('charter ✓') : chalk.yellow('charter missing')}\n`); } } export async function connectRemove(slug: string): Promise { try { validateProductSlug(slug); } catch (err) { process.stderr.write(chalk.red(`mod8 connect: ${err instanceof Error ? err.message : String(err)}\n`)); process.exit(1); } const dir = productDirFor(slug); if (!existsSync(dir)) { process.stderr.write(chalk.yellow(`mod8 connect: no product "${slug}" at ${dir}\n`)); process.exit(1); } await fs.rm(dir, { recursive: true, force: true }); process.stdout.write(chalk.green(`✓ removed ${slug}\n`)); } export async function connectAddAdapter(slug: string, adapterId: string): Promise { try { validateProductSlug(slug); } catch (err) { process.stderr.write(chalk.red(`${err instanceof Error ? err.message : String(err)}\n`)); process.exit(1); } // Ensure adapters are loaded so we know what's supported. const { loadAllAdapters, get } = await import('../loop/adapters/registry.js'); await loadAllAdapters().catch(() => {}); const adapter = get(adapterId); if (!adapter) { const all = listAdapters().map((a) => a.id).join(', '); process.stderr.write(chalk.red(`mod8 connect: unknown adapter "${adapterId}"\n`) + chalk.dim(` available: ${all}\n`)); process.exit(1); } const ctx = buildProductContext(slug, process.cwd(), 0); const path = connectorPath(ctx, adapterId); if (existsSync(path)) { process.stderr.write(chalk.yellow(`mod8 connect: ${adapterId} creds already exist at ${path}\n`) + chalk.dim(' delete the file first if you want to re-paste.\n')); process.exit(1); } process.stdout.write(chalk.bold(`mod8 connect add-adapter — ${slug} / ${adapterId}\n`)); process.stdout.write(chalk.dim(`adapter: ${adapter.label} (${adapter.kind})\n\n`)); // Per-adapter prompt — for now, prompts for common fields based // on adapter id. Phase 4+ replaces this with per-adapter // connect() hooks that drive their own OAuth flow. const rl = createInterface({ input: process.stdin, output: process.stdout }); const ask = (q: string): Promise => new Promise((res) => rl.question(q, (a) => res(a.trim()))); let creds: Record = { schemaVersion: 1, adapter: adapterId, authType: 'pat', createdAt: new Date().toISOString() }; try { if (adapterId === 'github') { creds.token = await ask('GitHub PAT (or leave blank to use GITHUB_TOKEN env): '); creds.ownerRepo = await ask('owner/repo (or leave blank to auto-detect from `git remote`): '); } else if (adapterId === 'vercel') { creds.token = await ask('Vercel API token: '); creds.projectId = await ask('project id (optional): '); creds.teamId = await ask('team id (optional): '); } else if (adapterId === 'plausible') { creds.token = await ask('Plausible Stats API key: '); creds.siteId = await ask('site id (e.g. example.com): '); creds.host = await ask('host (optional, blank for plausible.io): '); } else if (adapterId === 'posthog') { creds.token = await ask('PostHog personal API key: '); creds.projectId = await ask('project id: '); creds.host = await ask('host (optional, blank for us.posthog.com): '); } else if (adapterId === 'ga4') { creds.accessToken = await ask('GA4 OAuth access token: '); creds.propertyId = await ask('property id (e.g. properties/123456): '); creds.authType = 'oauth'; } else if (adapterId === 'stripe') { creds.token = await ask('Stripe restricted API key (read scopes): '); } else if (adapterId === 'slack' || adapterId === 'discord') { creds.webhookUrl = await ask('incoming-webhook URL: '); creds.channel = await ask('channel name (display only, optional): '); } else { creds.token = await ask('API key / token: '); } } finally { rl.close(); } // Strip empties. for (const [k, v] of Object.entries(creds)) { if (v === '' || v === undefined) delete creds[k]; } await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 }); await fs.writeFile(path, JSON.stringify(creds, null, 2), { mode: 0o600 }); process.stdout.write(chalk.green(`✓ stored ${adapterId} creds at ${path}\n`)); // Validate if adapter exposes validate(). if (adapter.validate) { try { const v = await adapter.validate(ctx, creds as never); if (v.ok) process.stdout.write(chalk.green(' ✓ adapter validated against remote\n')); else process.stdout.write(chalk.yellow(` ⚠ validation warning: ${v.detail}\n`)); } catch (err) { process.stdout.write(chalk.yellow(` ⚠ validation skipped: ${err instanceof Error ? err.message : String(err)}\n`)); } } } /** `mod8 loop pause --until ` writes paused_until into the * product's policy.yaml in-place (preserves comments? best-effort — * re-renders the whole file). Effective autonomy drops to L1 until * the date passes (see policy.effectiveAutonomy). */ export async function pauseLoop(slug: string, untilIso: string): Promise { const ctx = buildProductContext(slug, process.cwd(), 0); const path = productFiles.policyYaml(ctx); if (!existsSync(path)) { process.stderr.write(chalk.red(`mod8 loop pause: policy.yaml missing for ${slug}\n`)); process.exit(1); } // Validate date. const ts = Date.parse(untilIso); if (!Number.isFinite(ts)) { process.stderr.write(chalk.red(`mod8 loop pause: invalid --until "${untilIso}" — use ISO date (e.g. 2026-08-15)\n`)); process.exit(1); } // Edit policy.yaml in-place — find/replace paused_until or append. let raw = await fs.readFile(path, 'utf8'); const line = `paused_until: ${untilIso}`; if (/^paused_until:.*$/m.test(raw)) { raw = raw.replace(/^paused_until:.*$/m, line); } else { raw = raw.trimEnd() + '\n' + line + '\n'; } await fs.writeFile(path, raw, { mode: 0o600 }); process.stdout.write(chalk.green(`✓ loop paused until ${untilIso}`) + chalk.dim(' (effective autonomy drops to L1 until that date)\n')); }