diff --git a/README.md b/README.md index e68f68f..35cf55b 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ The skills CLI decides. With one agent it copies the skills into that agent's fo | `-h, --help` | Show the help | | `-v, --version` | Show the version | -`--modules` takes module codes: `method` (alias `bmm`), `toolsmith`, `founder`, `tea`, `bmad-loop` (alias `loop`) and `creative` (alias `cis`). Without `--modules`, `--yes` installs `method` and `toolsmith`. The core tools module installs on every run. A module that needs another brings it along: `bmad-loop` installs `method` too. `creative` replaces the Creative Intelligence Suite: in a project that holds the old suite, the picker ticks `creative` and `update` installs it, and `bmad setup` offers to remove the old skills. Each module installs whole, with one `npx skills add -s '*'` for its folder; a module already installed with nothing missing is skipped. +`--modules` takes module codes: `method` (alias `bmm`), `toolsmith`, `tea`, `bmad-loop` (alias `loop`), `creative` (alias `cis`) and `founder`. Without `--modules`, `--yes` installs `method` and `toolsmith`. The core tools module installs on every run. A module that needs another brings it along: `tea` and `bmad-loop` install `method` too. `creative` replaces the Creative Intelligence Suite: in a project that holds the old suite, the picker ticks `creative` and `update` installs it, and `bmad setup` offers to remove the old skills. Each module installs whole, with one `npx skills add -s '*'` for its folder; a module already installed with nothing missing is skipped. ### A branch or tag diff --git a/messages.yaml b/messages.yaml index 62a595d..0fd2cd0 100644 --- a/messages.yaml +++ b/messages.yaml @@ -1,27 +1,44 @@ -# The v6 wordmark: logoWide from 101 columns, logoNarrow from 48, none below. +# The v7 banner: logoMark beside logoWide from 116 columns, beside stacked logoNarrow from 78, text intro below 78. +logoMark: |- + ████████▄ ███▄ ▄███ + ███ ███ █████▄█████ + ████████▀ ███▀███▀███ + ███ ███ ███ ▀ ███ + ████████▀ ███ ███ + ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄███ + ███ ███ ███ + ▄██████████ ███ ███ + ███▄▄▄▄▄███ ▀████████ + logoWide: |- - ██████╗ ███╗ ███╗ █████╗ ██████╗ ███╗ ███╗███████╗████████╗██╗ ██╗ ██████╗ ██████╗ ™ - ██╔══██╗████╗ ████║██╔══██╗██╔══██╗ ████╗ ████║██╔════╝╚══██╔══╝██║ ██║██╔═══██╗██╔══██╗ - ██████╔╝██╔████╔██║███████║██║ ██║ ██╔████╔██║█████╗ ██║ ███████║██║ ██║██║ ██║ - ██╔══██╗██║╚██╔╝██║██╔══██║██║ ██║ ██║╚██╔╝██║██╔══╝ ██║ ██╔══██║██║ ██║██║ ██║ - ██████╔╝██║ ╚═╝ ██║██║ ██║██████╔╝ ██║ ╚═╝ ██║███████╗ ██║ ██║ ██║╚██████╔╝██████╔╝ - ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ + ██▀▀▀█▄ ██▄ ▄██ ██ ██▄ ▄██ ██ ██ ██ + ██▄▄▄█▀ ██▀█▀██ ▀▀▀██▄ ▄█▀▀▀██ ██▀█▀██ ▄█▀▀▀█▄ ▀▀██▀▀ ███▀▀█▄ ▄█▀▀▀█▄ ▄█▀▀▀██ + ██▀▀▀█▄ ██ ▀ ██ ▄█▀▀▀██ ██ ██ ██ ▀ ██ ███████ ██ ██ ██ ██ ██ ██ ██ + ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ▄▄ ██ ▄ ██ ██ ██ ██ ██ ██ + ▀▀▀▀▀▀ ▀▀ ▀▀ ▀▀▀▀▀▀ ▀▀▀▀▀▀ ▀▀ ▀▀ ▀▀▀▀▀ ▀▀▀ ▀▀ ▀▀ ▀▀▀▀▀ ▀▀▀▀▀▀ logoNarrow: |- - ██████╗ ███╗ ███╗ █████╗ ██████╗ ™ - ██╔══██╗████╗ ████║██╔══██╗██╔══██╗ - ██████╔╝██╔████╔██║███████║██║ ██║ - ██╔══██╗██║╚██╔╝██║██╔══██║██║ ██║ - ██████╔╝██║ ╚═╝ ██║██║ ██║██████╔╝ - ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ + ██▀▀▀█▄ ██▄ ▄██ ██ + ██▄▄▄█▀ ██▀█▀██ ▀▀▀██▄ ▄█▀▀▀██ + ██▀▀▀█▄ ██ ▀ ██ ▄█▀▀▀██ ██ ██ + ██ ██ ██ ██ ██ ██ ██ ██ + ▀▀▀▀▀▀ ▀▀ ▀▀ ▀▀▀▀▀▀ ▀▀▀▀▀▀ -credit: Build More, Architect Dreams · © BMad Code + ██▄ ▄██ ██ ██ ██ + ██▀█▀██ ▄█▀▀▀█▄ ▀▀██▀▀ ███▀▀█▄ ▄█▀▀▀█▄ ▄█▀▀▀██ + ██ ▀ ██ ███████ ██ ██ ██ ██ ██ ██ ██ + ██ ██ ██ ▄▄ ██ ▄ ██ ██ ██ ██ ██ ██ + ▀▀ ▀▀ ▀▀▀▀▀ ▀▀▀ ▀▀ ▀▀ ▀▀▀▀▀ ▀▀▀▀▀▀ -title: BMad Installer +eyebrow: "BMad Agent as Chief of Staff · Fully scale-adaptive facilitation engine" intro: |- - Installs BMad modules as agent skills. Free and open source. - Docs: https://docs.bmad-method.org + Expert AI agents that facilitate the best in you and your team. + Crafted modules for AI SDLC, strategy, creative, and building dreams. + +credit: "Free & open source · Docs: https://docs.bmad-method.org · © BMad Code" + +title: "BMad Installer V7" updateAvailable: |- You are using version {current} but {latest} is available. @@ -84,7 +101,7 @@ legacyNoV7: |- existingInstallPrompt: "BMad is already installed here. What do you want to do?" -existingInstallModify: "Add or change modules" +existingInstallModify: "Add modules or coding agents" existingInstallUpdate: "Update what is installed" @@ -94,14 +111,28 @@ installedSuffix: "(installed {version})" installedSuffixNoVersion: "(installed)" +installedVersionTag: "v{version}" + +installedTagNoVersion: "installed" + modulesPrompt: "Which modules do you want?" +modulesNone: "none" + +moduleRequiredTag: "[required by {by}]" + +moduleNotice: "↳ {notice}" + +moduleAutoSelected: "Auto-selected {modules} (required by {by})." + +moduleLockedBy: "{module} stays selected — required by {by} (untick {by} first)." + deprecatedModule: "{module} is deprecated. {reason}" modulesRequired: "Also installing {modules}: a module you picked needs it." modulesKept: |- - Still installed: {modules}. This installer never removes anything. + Still installed: {modules}. Ask the BMad Agent to remove a module, or run npx skills remove. agentsPrompt: "Which coding agents should get the skills?" @@ -183,21 +214,15 @@ summaryModuleGroup: "{names} ({version})" summaryAgents: "Agents {agents}" -summaryNextSetup: |- - Next: open your coding agent in this project and ask the BMad Agent - to run bmad setup, which finishes the install. Then, if you are - unsure what BMad and your installed modules can do, ask the BMad - Agent for a tour or what to do next. +summaryNextSetup: "Next Start your coding agent and say 'bmad setup'" -summaryNextCurrent: |- - Next: if you are unsure what BMad and your installed modules can do, - ask the BMad Agent in your coding agent for a tour or what to do next. +summaryNextCurrent: "Next Start your coding agent and say 'bmad help'" -summaryNextOther: "Next: {next}" +summaryNextOther: "Next {next}" universalAgentName: "Shared .agents/skills folder" -updateLater: "Update later: npx bmad-method update" +updateLater: "Update later: say 'bmad update' in your agent, or npx bmad-method update" repeatInstall: |- Same install without prompts: diff --git a/modules.yaml b/modules.yaml index e7dcaf1..a873ebd 100644 --- a/modules.yaml +++ b/modules.yaml @@ -13,35 +13,30 @@ modules: - code: method aliases: [bmm] name: BMad Method - description: Plan, spec and build software with agile AI agents + description: Facilitated AI SDLC — discovery, specs, UX, architecture & build source: bmad-code-org/BMAD-METHOD/skills/method record: bmod-method default: true - code: toolsmith name: BMad Toolsmith - description: Build, convert, review and package skills, agents and modules + description: Forge custom skills, expert personas & org/community BMODs — with evals source: bmad-code-org/BMAD-METHOD/skills/toolsmith record: bmod-toolsmith default: true - - code: founder - name: BMad Founder - description: Nadia the Founder Advisor, for the business side of a startup - source: bmad-code-org/BMAD-METHOD/skills/founder - record: bmad-founder-agent-advisor - - code: tea name: BMad Test Architect - description: Murat, for test planning, automation, evaluation and release decisions + description: Enterprise test strategy, automation, traceability & release gates # The repository root also holds test fixture skills, so the source is its skills folder. source: bmad-code-org/bmad-method-test-architecture-enterprise/skills record: bmod-tea + requires: [method] - code: bmad-loop aliases: [loop] name: BMad Loop - description: Runs stories unattended (implement, review, verify, commit). Early beta + description: Unattended story runner — implement, review, verify, commit · beta source: bmad-code-org/bmad-loop/skills record: bmod-bmad-loop requires: [method] @@ -50,6 +45,12 @@ modules: - code: creative aliases: [cis] name: BMad Creative - description: Clio the Creative Director, for stories, talks, your voice, visuals and hard non-code problems + description: Creative direction for talks, stories, decks, voice & hard problems source: bmad-code-org/BMAD-METHOD/skills/creative record: bmad-creative-agent-director + + - code: founder + name: BMad Founder + description: Founder & venture advisory — validation, models, pricing & decks + source: bmad-code-org/BMAD-METHOD/skills/founder + record: bmad-founder-agent-advisor diff --git a/package-lock.json b/package-lock.json index d1f9afc..6a79917 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,8 @@ "version": "7.0.0-next.0", "license": "MIT", "dependencies": { - "@clack/prompts": "^1.9.0", + "@clack/core": "1.6.0", + "@clack/prompts": "1.9.0", "@vercel/detect-agent": "^1.2.7", "cross-spawn": "^7.1.0", "skills": "1.9.1", diff --git a/package.json b/package.json index aab6923..2cff393 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,8 @@ "agents": "node tools/generate-agents.js" }, "dependencies": { - "@clack/prompts": "^1.9.0", + "@clack/core": "1.6.0", + "@clack/prompts": "1.9.0", "cross-spawn": "^7.1.0", "yaml": "^2.9.1", "@vercel/detect-agent": "^1.2.7", diff --git a/src/commands/ending.js b/src/commands/ending.js index bf1d203..946eaae 100644 --- a/src/commands/ending.js +++ b/src/commands/ending.js @@ -42,7 +42,7 @@ export async function endRun(deps, run) { updated: run.updated, fallbackModules: run.fallbackModules, }) - prompts.showNote(summary.body, summary.title) + prompts.showNote(summary.body, summary.title, { accentAfterBlank: true }) if (!run.updated) { const commands = [message(messages, 'updateLater')] diff --git a/src/commands/install.js b/src/commands/install.js index 79ccc7f..1e8a7d2 100644 --- a/src/commands/install.js +++ b/src/commands/install.js @@ -52,7 +52,7 @@ export async function install(options, deps) { prompts.warn(message(messages, 'deprecatedModule', { module: module.name, reason: module.deprecated })) } } - const kept = modules.filter((module) => existing.codes.includes(module.code) && !chosen.some((picked) => picked.code === module.code)) + const kept = modules.filter((module) => !module.always && existing.codes.includes(module.code) && !chosen.some((picked) => picked.code === module.code)) if (kept.length > 0) { prompts.warn(message(messages, 'modulesKept', { modules: kept.map((module) => module.name).join(', ') })) } diff --git a/src/prompts.js b/src/prompts.js index ad633dc..503f968 100644 --- a/src/prompts.js +++ b/src/prompts.js @@ -1,29 +1,54 @@ -import { styleText } from 'node:util' +import { stripVTControlCharacters, styleText } from 'node:util' +import { MultiSelectPrompt } from '@clack/core' import { + MULTISELECT_INSTRUCTIONS, + S_BAR, + S_CHECKBOX_ACTIVE, + S_CHECKBOX_INACTIVE, + S_CHECKBOX_SELECTED, autocompleteMultiselect, box, cancel, confirm as confirmPrompt, + formatInstructionFooter, intro, isCancel, + limitOptions, log, - multiselect, note, outro, select, spinner, + symbol, + symbolBar, text, + unicodeOr, } from '@clack/prompts' import { UNIVERSAL_AGENT } from './agents.js' import { message } from './messages.js' -import { installedLabel } from './report.js' +import { stripBrandPrefix } from './report.js' -const WIDE_LOGO_COLUMNS = 101 -const NARROW_LOGO_COLUMNS = 48 +const WIDE_LOGO_COLUMNS = 116 +const NARROW_LOGO_COLUMNS = 78 +const BA_SPLIT_COLUMN = 11 +const POINTER_ACTIVE = unicodeOr('›', '>') +const TILE_COBALT = /** @type {const} */ ([29, 55, 122]) +const LOGO_WHITE = /** @type {const} */ ([255, 255, 255]) +const ACCENT_PERIWINKLE = /** @type {const} */ ([147, 180, 255]) +const BOX_SLATE = /** @type {const} */ ([56, 67, 87]) + +/** @typedef {readonly [number, number, number]} Rgb */ +/** @typedef {Parameters[0]} StyleFormat */ +/** @typedef {'none' | 'ansi' | 'truecolor'} ColorLevel */ +/** @typedef {import('node:stream').Writable & { columns?: number, hasColors?: (count?: number) => boolean }} PromptOutput */ +/** @typedef {import('node:stream').Readable} PromptInput */ /** @typedef {import('./agents.js').Agent} Agent */ /** @typedef {import('./modules.js').ModuleDefinition} ModuleDefinition */ -/** @typedef {{ options: { value: string, label: string, hint: string }[], initialValues: string[] }} Picker */ +/** @typedef {{ value: string, label: string, hint: string }} PickerOption */ +/** @typedef {PickerOption & { tag: string, requires: string[] }} ModulePickerOption */ +/** @typedef {{ options: PickerOption[], initialValues: string[] }} Picker */ +/** @typedef {{ options: ModulePickerOption[], initialValues: string[], initialNotice: string }} ModulePicker */ export class Cancelled extends Error { name = 'Cancelled' @@ -39,38 +64,225 @@ function ensure(value) { return /** @type {Exclude} */ (/** @type {unknown} */ (value)) } -/** @param {Record} messages */ -export function showIntro(messages) { - const columns = process.stdout.columns || 80 - if (columns >= NARROW_LOGO_COLUMNS) showLogo(messages, columns) - intro(message(messages, 'title')) - log.message(message(messages, 'intro')) +/** + * Resolves colour capability from env overrides first, then the target output stream. + * @param {PromptOutput} [output] + * @returns {ColorLevel} + */ +export function colorLevel(output = process.stdout) { + const { FORCE_COLOR, NO_COLOR, NODE_DISABLE_COLORS, COLORTERM } = process.env + if (FORCE_COLOR !== undefined) { + if (FORCE_COLOR === '0' || FORCE_COLOR === 'false') return 'none' + if (FORCE_COLOR === '3') return 'truecolor' + return COLORTERM === 'truecolor' || COLORTERM === '24bit' ? 'truecolor' : 'ansi' + } + if ((NO_COLOR !== undefined && NO_COLOR !== '') || (NODE_DISABLE_COLORS !== undefined && NODE_DISABLE_COLORS !== '')) { + return 'none' + } + if (typeof output.hasColors === 'function') { + if (output.hasColors(2 ** 24)) return 'truecolor' + if (output.hasColors()) return 'ansi' + return 'none' + } + return 'none' +} + +/** + * @param {StyleFormat} fmt + * @param {string} str + * @param {PromptOutput} [output] + */ +function tone(fmt, str, output = process.stdout) { + return colorLevel(output) === 'none' ? str : styleText(fmt, str, { validateStream: false }) +} + +/** + * 24-bit TrueColor styling on truecolor streams, falling back to 16-colour ANSI on older terminals + * and plain text when colour is disabled (`NO_COLOR`, `FORCE_COLOR=0`, or non-TTY streams). + * @param {string} str + * @param {{ fg?: Rgb, bg?: Rgb, bold?: boolean, fallback?: StyleFormat }} codes + * @param {PromptOutput} [output] + */ +function paint(str, { fg, bg, bold = false, fallback }, output = process.stdout) { + const level = colorLevel(output) + if (level === 'none') return str + if (level === 'ansi') { + const fmt = fallback ?? (bold ? 'bold' : undefined) + return fmt ? styleText(fmt, str, { validateStream: false }) : str + } + const open = [ + ...(bold ? ['1'] : []), + ...(fg ? [`38;2;${fg[0]};${fg[1]};${fg[2]}`] : []), + ...(bg ? [`48;2;${bg[0]};${bg[1]};${bg[2]}`] : []), + ] + const close = [ + ...(bold ? ['22'] : []), + ...(fg ? ['39'] : []), + ...(bg ? ['49'] : []), + ] + return open.length > 0 ? `\x1b[${open.join(';')}m${str}\x1b[${close.join(';')}m` : str +} + +/** + * Word-wraps a plain line to `maxWidth` columns so narrow guide-rail fallbacks keep the rail intact. + * @param {string} line + * @param {number} maxWidth + * @returns {string[]} + */ +function wrapPlain(line, maxWidth) { + const words = line.split(' ') + /** @type {string[]} */ + const out = [] + let current = '' + for (const word of words) { + if (!current) current = word + else if ([...current].length + 1 + [...word].length <= maxWidth) current = `${current} ${word}` + else { + out.push(current) + current = word + } + } + if (current || out.length === 0) out.push(current) + return out +} + +/** + * @param {Record} messages + * @param {PromptOutput} [output] + */ +export function showIntro(messages, output = process.stdout) { + const columns = output.columns || 80 + if (columns >= NARROW_LOGO_COLUMNS) showLogo(messages, columns, output) + intro( + paint(` ${message(messages, 'title')} `, { fg: LOGO_WHITE, bg: TILE_COBALT, bold: true, fallback: ['bgBlue', 'whiteBright', 'bold'] }, output), + { output }, + ) + if (columns < NARROW_LOGO_COLUMNS) { + const maxWidth = Math.max(20, columns - 3) + const eyebrowLines = wrapPlain(message(messages, 'eyebrow'), maxWidth) + .map((line) => paint(line, { fg: ACCENT_PERIWINKLE, fallback: 'cyan' }, output)) + const introLines = message(messages, 'intro') + .split('\n') + .flatMap((line) => wrapPlain(line, maxWidth)) + const creditLines = wrapPlain(message(messages, 'credit'), maxWidth) + .map((line) => tone('dim', line, output)) + log.message([...eyebrowLines, ...introLines, ...creditLines].join('\n'), { output }) + } } /** * @param {Record} messages * @param {number} columns + * @param {PromptOutput} output */ -function showLogo(messages, columns) { - const lines = message(messages, columns >= WIDE_LOGO_COLUMNS ? 'logoWide' : 'logoNarrow').split('\n') - const width = Math.max(...lines.map((line) => line.length)) - // Padded to one width so the centred box keeps the letters aligned. - const logo = lines.map((line) => styleText('blue', line.padEnd(width))).join('\n') - box(`${logo}\n\n${styleText('dim', message(messages, 'credit'))}`, '', { +function showLogo(messages, columns, output) { + const markLines = message(messages, 'logoMark').split('\n') + const markWidth = Math.max(...markLines.map((line) => [...line].length)) + const tileWidth = markWidth + 2 + const blankTile = ' '.repeat(tileWidth) + const tile = [ + { plain: blankTile, styled: paint(blankTile, { bg: TILE_COBALT, fallback: 'bgBlue' }, output) }, + ...markLines.map((line) => { + const padded = [...`${line}${' '.repeat(markWidth - [...line].length)}`] + const leftBa = ` ${padded.slice(0, BA_SPLIT_COLUMN).join('')}` + const rightMd = `${padded.slice(BA_SPLIT_COLUMN).join('')} ` + return { + plain: `${leftBa}${rightMd}`, + styled: + paint(leftBa, { fg: LOGO_WHITE, bg: TILE_COBALT, fallback: ['bgBlue', 'whiteBright'] }, output) + + paint(rightMd, { fg: ACCENT_PERIWINKLE, bg: TILE_COBALT, fallback: ['bgBlue', 'cyanBright'] }, output), + } + }), + { plain: blankTile, styled: paint(blankTile, { bg: TILE_COBALT, fallback: 'bgBlue' }, output) }, + ] + + const eyebrow = message(messages, 'eyebrow') + const introLines = message(messages, 'intro').split('\n') + const credit = message(messages, 'credit') + const copyRows = [ + { plain: eyebrow, styled: paint(eyebrow, { fg: ACCENT_PERIWINKLE, fallback: 'cyan' }, output) }, + ...introLines.map((line) => ({ plain: line, styled: line })), + { plain: '', styled: '' }, + { plain: credit, styled: tone('dim', credit, output) }, + ] + + const wide = columns >= WIDE_LOGO_COLUMNS + /** @type {{ plain: string, styled: string }[]} */ + let rows + if (wide) { + const wordmark = message(messages, 'logoWide').split('\n') + const rightRows = [ + ...wordmark.map((line) => ({ + plain: line, + styled: paint(line, { fg: LOGO_WHITE, bold: true, fallback: ['whiteBright', 'bold'] }, output), + })), + { plain: '', styled: '' }, + ...copyRows, + ] + const count = Math.max(tile.length, rightRows.length) + rows = Array.from({ length: count }, (_, i) => { + const left = tile[i] ?? { plain: blankTile, styled: blankTile } + const right = rightRows[i] ?? { plain: '', styled: '' } + return right.plain + ? { plain: `${left.plain} ${right.plain}`, styled: `${left.styled} ${right.styled}` } + : left + }) + } else { + const narrowWordmark = message(messages, 'logoNarrow').split('\n') + const count = Math.max(tile.length, narrowWordmark.length) + const topRows = Array.from({ length: count }, (_, i) => { + const left = tile[i] ?? { plain: blankTile, styled: blankTile } + const word = narrowWordmark[i] ?? '' + return word + ? { + plain: `${left.plain} ${word}`, + styled: `${left.styled} ${paint(word, { fg: LOGO_WHITE, bold: true, fallback: ['whiteBright', 'bold'] }, output)}`, + } + : left + }) + rows = [...topRows, { plain: '', styled: '' }, ...copyRows] + } + + let width = Math.max(...rows.map((row) => [...row.plain].length)) + if (width % 2 !== 0) width += 1 + const body = ['', ...rows.map((row) => row.styled + ' '.repeat(width - [...row.plain].length)), ''].join('\n') + box(body, '', { contentAlign: 'center', + contentPadding: wide ? 3 : 2, width: 'auto', rounded: true, withGuide: false, - formatBorder: (text) => styleText('blue', text), + formatBorder: (border) => paint(border, { fg: BOX_SLATE, fallback: 'gray' }, output), + output, }) } /** - * @param {string} text + * Renders a Clack note box. When `accentAfterBlank` is set (used by the closing install/update + * summary), the block after the blank separator line is highlighted without dimming other notes. + * @param {string} body * @param {string} [title] + * @param {{ accentAfterBlank?: boolean, output?: PromptOutput }} [options] */ -export function showNote(text, title) { - note(text, title) +export function showNote(body, title, options) { + const output = options?.output ?? process.stdout + let content = body + if (options?.accentAfterBlank) { + let afterBlank = false + content = body + .split('\n') + .map((line) => { + if (line === '') { + afterBlank = true + return '' + } + return afterBlank && line + ? paint(line, { fg: ACCENT_PERIWINKLE, bold: true, fallback: ['cyan', 'bold'] }, output) + : line + }) + .join('\n') + } + note(content, title, { output }) } /** @param {string} text */ @@ -136,25 +348,134 @@ export async function confirm(question, initial = true) { return ensure(await confirmPrompt({ message: question, initialValue: initial })) } +/** + * @param {string} code + * @param {Map} byCode + * @returns {string[]} + */ +function dependenciesOf(code, byCode) { + /** @type {Set} */ + const seen = new Set() + const queue = [...(byCode.get(code)?.requires ?? [])] + while (queue.length > 0) { + const next = queue.shift() + if (!next || seen.has(next) || !byCode.has(next)) continue + seen.add(next) + queue.push(...(byCode.get(next)?.requires ?? [])) + } + return [...seen] +} + +/** + * Maps each required module code to the display names of currently selected modules that depend on it. + * @param {readonly string[]} selected + * @param {readonly ModulePickerOption[]} shown + * @returns {Map} + */ +export function requiredByNames(selected, shown) { + const byCode = new Map(shown.map((opt) => [opt.value, opt])) + /** @type {Map} */ + const map = new Map() + for (const code of selected) { + const owner = byCode.get(code) + if (!owner) continue + for (const dep of dependenciesOf(code, byCode)) { + const list = map.get(dep) ?? [] + list.push(owner.label) + map.set(dep, list) + } + } + return map +} + +/** + * Keeps module dependencies selected as the user toggles checkboxes: ticking a module auto-selects + * what it requires, and trying to untick a required module while its dependent stays ticked keeps + * it selected with an inline explanation. + * @param {readonly string[]} previous + * @param {readonly string[]} next + * @param {readonly ModulePickerOption[]} shown + * @param {Record} messages + * @returns {{ values: string[], notice: string }} + */ +export function reconcileModuleSelection(previous, next, shown, messages) { + const prevSet = new Set(previous) + const nextSet = new Set(next) + const byCode = new Map(shown.map((opt) => [opt.value, opt])) + let notice = '' + + for (const opt of shown) { + if (!prevSet.has(opt.value) || nextSet.has(opt.value)) continue + const dependents = shown.filter( + (other) => nextSet.has(other.value) && prevSet.has(other.value) && dependenciesOf(other.value, byCode).includes(opt.value), + ) + if (dependents.length > 0) { + nextSet.add(opt.value) + notice = message(messages, 'moduleLockedBy', { + module: opt.label, + by: dependents.map((dep) => dep.label).join(', '), + }) + } + } + + /** @type {Set} */ + const missing = new Set() + for (const opt of shown) { + if (!nextSet.has(opt.value)) continue + for (const dep of dependenciesOf(opt.value, byCode)) { + if (!nextSet.has(dep)) missing.add(dep) + } + } + if (missing.size > 0) { + for (const dep of missing) nextSet.add(dep) + const pulled = shown.filter((opt) => missing.has(opt.value)).map((opt) => opt.label) + const triggers = shown + .filter((opt) => !missing.has(opt.value) && nextSet.has(opt.value) && dependenciesOf(opt.value, byCode).some((dep) => missing.has(dep))) + .map((opt) => opt.label) + notice = message(messages, 'moduleAutoSelected', { + modules: pulled.join(', '), + by: triggers.join(', '), + }) + } + + return { + values: shown.filter((opt) => nextSet.has(opt.value)).map((opt) => opt.value), + notice, + } +} + /** * @param {Record} messages * @param {ModuleDefinition[]} modules * @param {{ installedCodes: string[], installedVersions: Record }} options - * @returns {Picker} + * @returns {ModulePicker} */ export function modulePicker(messages, modules, options) { const { installedCodes, installedVersions } = options const fresh = installedCodes.length === 0 const shown = modules.filter((module) => !module.always) - return { - options: shown.map((module) => ({ + const pickerOptions = shown.map((module) => { + const installed = installedCodes.includes(module.code) + const version = installedVersions[module.code] + const tag = installed + ? (version ? message(messages, 'installedVersionTag', { version }) : message(messages, 'installedTagNoVersion')) + : '' + return { value: module.code, - label: installedCodes.includes(module.code) ? installedLabel(messages, module.name, installedVersions[module.code]) : module.name, + label: module.name, + tag, hint: module.description, - })), - initialValues: shown - .filter((module) => [module.code, ...(module.aliases ?? [])].some((code) => installedCodes.includes(code)) || (fresh && module.default)) - .map((module) => module.code), + requires: module.requires ?? [], + } + }) + const rawInitial = shown + .filter((module) => [module.code, ...(module.aliases ?? [])].some((code) => installedCodes.includes(code)) || (fresh && module.default)) + .map((module) => module.code) + const reconciled = reconcileModuleSelection([], rawInitial, pickerOptions, messages) + return { + options: pickerOptions, + initialValues: reconciled.values, + initialNotice: reconciled.notice, } } @@ -162,14 +483,87 @@ export function modulePicker(messages, modules, options) { * @param {Record} messages * @param {ModuleDefinition[]} modules * @param {{ installedCodes: string[], installedVersions: Record }} options + * @param {{ input?: PromptInput, output?: PromptOutput }} [io] * @returns {Promise} */ -export async function chooseModules(messages, modules, options) { - return ensure(await multiselect({ - message: message(messages, 'modulesPrompt'), - ...modulePicker(messages, modules, options), - required: false, - })) +export async function chooseModules(messages, modules, options, io) { + const input = io?.input ?? process.stdin + const output = io?.output ?? process.stdout + const picker = modulePicker(messages, modules, options) + const nameWidth = Math.max(...picker.options.map((opt) => opt.label.length)) + 2 + const maxTag = Math.max(0, ...picker.options.map((opt) => opt.tag.length)) + const tagWidth = maxTag > 0 ? maxTag + 2 : 0 + const title = message(messages, 'modulesPrompt') + + let previous = [...picker.initialValues] + let notice = picker.initialNotice + + const prompt = new MultiSelectPrompt({ + options: picker.options, + initialValues: picker.initialValues, + input, + output, + render() { + const selected = this.value ?? [] + const header = `${tone('gray', S_BAR, output)}\n${symbol(this.state)} ${title}\n` + if (this.state === 'submit') { + const picked = this.options + .filter((opt) => selected.includes(opt.value)) + .map((opt) => tone('dim', opt.label, output)) + .join(tone('dim', ', ', output)) || tone('dim', message(messages, 'modulesNone'), output) + return `${header}${tone('gray', S_BAR, output)} ${picked}` + } + if (this.state === 'cancel') { + const cancelled = this.options + .filter((opt) => selected.includes(opt.value)) + .map((opt) => tone(['strikethrough', 'dim'], opt.label, output)) + .join(tone('dim', ', ', output)) + return cancelled + ? `${header}${tone('gray', S_BAR, output)} ${cancelled}\n${tone('gray', S_BAR, output)}` + : `${header}${tone('gray', S_BAR, output)}` + } + + const reqMap = requiredByNames(selected, this.options) + const bar = `${symbolBar(this.state) ?? tone('cyan', S_BAR, output)} ` + const footerLines = formatInstructionFooter(output, MULTISELECT_INSTRUCTIONS, true) + const rows = limitOptions({ + output, + options: this.options, + cursor: this.cursor, + columnPadding: stripVTControlCharacters(bar).length, + rowPadding: header.split('\n').length + footerLines.length + (notice ? 2 : 1), + style: (opt, active) => { + const pointer = active ? paint(POINTER_ACTIVE, { fg: ACCENT_PERIWINKLE, fallback: 'cyan' }, output) : ' ' + const ticked = selected.includes(opt.value) + const check = ticked + ? tone('green', S_CHECKBOX_SELECTED, output) + : active + ? tone('cyan', S_CHECKBOX_ACTIVE, output) + : tone('dim', S_CHECKBOX_INACTIVE, output) + const paddedName = opt.label.padEnd(nameWidth) + const name = active ? paddedName : ticked ? tone('white', paddedName, output) : tone('dim', paddedName, output) + const tag = tagWidth > 0 ? paint(opt.tag.padEnd(tagWidth), { fg: ACCENT_PERIWINKLE, fallback: 'cyan' }, output) : '' + const desc = tone('dim', opt.hint, output) + const owners = reqMap.get(opt.value) ?? [] + const reqBadge = owners.length > 0 + ? ` ${tone('yellow', message(messages, 'moduleRequiredTag', { by: owners.map(stripBrandPrefix).join(', ') }), output)}` + : '' + return `${pointer} ${check} ${name}${tag}${desc}${reqBadge}` + }, + }) + const noticeLine = notice ? `\n${bar}${tone('yellow', message(messages, 'moduleNotice', { notice }), output)}` : '' + return `${header}${bar}${rows.join(`\n${bar}`)}${noticeLine}\n${footerLines.join('\n')}\n` + }, + }) + + prompt.on('key', () => { + const next = reconcileModuleSelection(previous, prompt.value ?? [], picker.options, messages) + prompt.value = next.values + previous = [...next.values] + notice = next.notice + }) + + return ensure(await prompt.prompt()) ?? [] } /** diff --git a/src/report.js b/src/report.js index 7d4b197..733da0f 100644 --- a/src/report.js +++ b/src/report.js @@ -156,6 +156,15 @@ function groupedModules(report, modules, messages) { .join('; ') } +/** + * Drops the leading `BMad ` prefix where the surrounding heading already carries the brand. + * @param {string} name + * @returns {string} + */ +export function stripBrandPrefix(name) { + return name.replace(/^BMad\s+/, '') +} + /** * The summary sits under "BMad is installed", so the brand prefix would only push the line past the box width. * @param {ModuleDefinition[]} modules @@ -163,7 +172,7 @@ function groupedModules(report, modules, messages) { * @returns {string} */ function shortModuleName(modules, code) { - return moduleName(modules, code).replace(/^BMad /, '') + return stripBrandPrefix(moduleName(modules, code)) } /** diff --git a/test/cli.test.js b/test/cli.test.js index 11707cf..7e2ce6d 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -182,7 +182,7 @@ test('main rejects an unknown --tools id before it prints anything else', async test('main rejects an unknown --modules code before it prints anything else', async () => { const { io, out, err } = fakeIo() assert.equal(await main(['-y', '-m', 'method,nope', '-t', 'claude-code'], io), 2) - assert.ok(err.join('').startsWith('Unknown module: nope\nModules: method, toolsmith, founder, tea, bmad-loop, creative, or a folder'), err.join('')) + assert.ok(err.join('').startsWith('Unknown module: nope\nModules: method, toolsmith, tea, bmad-loop, creative, founder, or a folder'), err.join('')) assert.equal(out.length, 0) }) diff --git a/test/commands/install.test.js b/test/commands/install.test.js index 37d0600..4ff6186 100644 --- a/test/commands/install.test.js +++ b/test/commands/install.test.js @@ -197,8 +197,17 @@ test('unticking an installed module keeps it and says so', async (t) => { await install(options({ directory: dir }), makeDeps({ prompts, skillsCli: cli, bmadScripts: scripts, cwd: dir, detect: heldBy(dir, '.claude/skills') })) - assert.ok(said.warns.includes(messages.modulesKept.replace('{modules}', 'BMad Method')), said.warns.join('\n')) + const expectedKept = messages.modulesKept.replace('{modules}', 'BMad Method') + assert.ok(said.warns.includes(expectedKept), said.warns.join('\n')) assert.deepEqual(only(requests).map((request) => request.source), ['bmad-code-org/BMAD-METHOD/skills/founder']) + + const flagRun = fakePrompts() + const flagCli = fakeSkillsCli({ lists: [[listed('bmad'), listed('bmod-core-tools'), listed('bmod-method')], RECORDS.map(listed)] }) + await install( + options({ directory: dir, yes: true, modules: 'founder' }), + makeDeps({ prompts: flagRun.prompts, skillsCli: flagCli.cli, bmadScripts: fakeBmadScripts({ statuses: [installed, installed] }).scripts, cwd: dir, detect: heldBy(dir, '.claude/skills') }), + ) + assert.ok(flagRun.said.warns.includes(expectedKept)) }) test('--modules with a folder installs that module whole next to the listed ones', async (t) => { diff --git a/test/messages.test.js b/test/messages.test.js index 7568834..8f1fc87 100644 --- a/test/messages.test.js +++ b/test/messages.test.js @@ -13,7 +13,13 @@ const NOTE_WIDTH = 74 /** @type {Record>} */ const keysWithValues = { + logoMark: {}, + logoWide: {}, + logoNarrow: {}, + eyebrow: {}, intro: {}, + credit: {}, + title: {}, updateAvailable: { current: '6.13.0-next.0', latest: '6.13.0-next.1', tag: 'next' }, nodeTooOld: { version: '20.11.0' }, nodeBelowSkillsFloor: { version: '22.13.0' }, @@ -33,7 +39,14 @@ const keysWithValues = { foundModules: {}, installedSuffix: { version: '6.13.0-next' }, installedSuffixNoVersion: {}, + installedVersionTag: { version: '7.0.0' }, + installedTagNoVersion: {}, modulesPrompt: {}, + modulesNone: {}, + moduleRequiredTag: { by: 'Loop' }, + moduleNotice: { notice: 'Auto-selected BMad Method.' }, + moduleAutoSelected: { modules: 'BMad Method', by: 'BMad Loop' }, + moduleLockedBy: { module: 'BMad Method', by: 'BMad Loop' }, deprecatedModule: { module: 'BMad Method', reason: 'Replaced by another module.' }, agentsPrompt: {}, agentsPlaceholder: {}, @@ -135,8 +148,10 @@ test('droppedFlags has one line for every dropped flag', () => { test('the ending names setup, the update command and every link once', () => { const next = message(loaded, 'summaryNextSetup') - assert.ok(next.includes('bmad setup')) - assert.ok(message(loaded, 'updateLater').includes('npx bmad-method update')) + assert.ok(next.includes("'bmad setup'")) + const updateLater = message(loaded, 'updateLater') + assert.ok(updateLater.includes("'bmad update'")) + assert.ok(updateLater.includes('npx bmad-method update')) const thanks = message(loaded, 'thanks') for (const link of [ 'https://blog.bmadcode.com', @@ -147,13 +162,15 @@ test('the ending names setup, the update command and every link once', () => { 'https://bmadcode.com/#contact', ]) { assert.ok(thanks.includes(link), `thanks is missing: ${link}`) - assert.equal(message(loaded, 'intro').includes(link), false, `intro repeats ${link}`) + for (const bannerKey of ['eyebrow', 'intro', 'credit']) { + assert.equal(message(loaded, bannerKey).includes(link), false, `${bannerKey} repeats ${link}`) + } } }) test('the prose blocks fit the clack note box without rewrapping', () => { const blocks = [ - 'intro', 'updateAvailable', 'nodeTooOld', 'nodeBelowSkillsFloor', 'uvMissing', 'wslWindowsNode', + 'eyebrow', 'intro', 'credit', 'updateAvailable', 'nodeTooOld', 'nodeBelowSkillsFloor', 'uvMissing', 'wslWindowsNode', 'needsTerminal', 'insideAgent', 'legacyManifest', 'legacyNoV7', 'modulesKept', 'firstInstallNotInProject', 'unknownTools', 'repeatInstall', 'nothingInstalled', 'nothingToUpdate', 'statusNoUv', 'cancelled', 'summaryNextSetup', 'summaryNextCurrent', 'thanks', 'droppedUninstall', ] @@ -164,10 +181,19 @@ test('the prose blocks fit the clack note box without rewrapping', () => { } }) -test('intro is two lines with the docs link', () => { - const text = message(loaded, 'intro') - assert.equal(text.split('\n').length, 2) - assert.ok(text.includes('https://docs.bmad-method.org')) +test('banner copy fits the 72-column narrow box and carries the docs link and v7 pill', () => { + assert.equal(message(loaded, 'title'), 'BMad Installer V7') + const eyebrow = message(loaded, 'eyebrow') + const intro = message(loaded, 'intro') + const credit = message(loaded, 'credit') + assert.ok(eyebrow.includes('BMad Agent as Chief of Staff')) + assert.ok(eyebrow.includes('scale-adaptive facilitation engine')) + assert.equal(intro.split('\n').length, 2) + assert.ok(credit.includes('https://docs.bmad-method.org')) + assert.ok(credit.includes('© BMad Code')) + for (const line of [eyebrow, ...intro.split('\n'), credit]) { + assert.ok([...line].length <= 72, `banner line exceeds 72 columns (${[...line].length}): ${line}`) + } }) test('render fills placeholders and throws when a value is missing', () => { diff --git a/test/modules.test.js b/test/modules.test.js index 9f47198..9b6133b 100644 --- a/test/modules.test.js +++ b/test/modules.test.js @@ -46,7 +46,7 @@ after(async () => { test('loads and validates the real modules.yaml', async () => { const modules = await loadModules() - assert.deepEqual(modules.map((module) => module.code), ['core-tools', 'method', 'toolsmith', 'founder', 'tea', 'bmad-loop', 'creative']) + assert.deepEqual(modules.map((module) => module.code), ['core-tools', 'method', 'toolsmith', 'tea', 'bmad-loop', 'creative', 'founder']) assert.equal(must(modules, 'core-tools').always, true) const method = must(modules, 'method') assert.deepEqual(method.aliases, ['bmm']) diff --git a/test/prompts.test.js b/test/prompts.test.js index a63fae6..a0fbbdc 100644 --- a/test/prompts.test.js +++ b/test/prompts.test.js @@ -1,9 +1,21 @@ import { test } from 'node:test' import assert from 'node:assert/strict' +import { PassThrough } from 'node:stream' +import { stripVTControlCharacters } from 'node:util' import { loadMessages } from '../src/messages.js' import { loadModules } from '../src/modules.js' import { loadAgents } from '../src/agents.js' -import { agentPicker, modulePicker } from '../src/prompts.js' +import { + Cancelled, + agentPicker, + chooseModules, + colorLevel, + modulePicker, + reconcileModuleSelection, + requiredByNames, + showIntro, + showNote, +} from '../src/prompts.js' /** @typedef {import('../src/modules.js').ModuleDefinition} ModuleDefinition */ @@ -20,20 +32,21 @@ function must(code) { const method = must('method') const fresh = { installedCodes: /** @type {string[]} */ ([]), installedVersions: {} } -test('the module picker hides the always modules', () => { +test('the module picker hides the always modules and keeps Order 3', () => { const picker = modulePicker(messages, modules, fresh) - assert.deepEqual(picker.options.map((option) => option.value), ['method', 'toolsmith', 'founder', 'tea', 'bmad-loop', 'creative']) + assert.deepEqual(picker.options.map((option) => option.value), ['method', 'toolsmith', 'tea', 'bmad-loop', 'creative', 'founder']) assert.equal(picker.options.some((option) => option.value === 'core-tools'), false) }) -test('a fresh install arrives with the default modules ticked', () => { +test('a fresh install arrives with the default modules ticked and empty version tags', () => { const picker = modulePicker(messages, modules, fresh) assert.deepEqual(picker.initialValues, ['method', 'toolsmith']) assert.equal(picker.options[0].label, 'BMad Method') + assert.equal(picker.options[0].tag, '') assert.equal(picker.options[0].hint, method.description) }) -test('an existing install ticks what is installed and labels its version', () => { +test('an existing install ticks what is installed and sets its version tag', () => { const picker = modulePicker(messages, modules, { installedCodes: ['core-tools', 'founder'], installedVersions: { founder: '6.13.0-next' }, @@ -41,15 +54,69 @@ test('an existing install ticks what is installed and labels its version', () => assert.deepEqual(picker.initialValues, ['founder']) assert.equal(picker.options[0].label, 'BMad Method') - assert.equal(picker.options.find((option) => option.value === 'founder')?.label, `${must('founder').name} ${messages.installedSuffix.replace('{version}', '6.13.0-next')}`) + assert.equal(picker.options[0].tag, '') + assert.equal(picker.options.find((option) => option.value === 'founder')?.tag, 'v6.13.0-next') }) -test('an installed module with no known version gets the plain suffix', () => { +test('an installed module with no known version gets the plain installed tag', () => { const picker = modulePicker(messages, modules, { installedCodes: ['method'], installedVersions: {} }) - assert.equal(picker.options[0].label, `BMad Method ${messages.installedSuffixNoVersion}`) + assert.equal(picker.options[0].label, 'BMad Method') + assert.equal(picker.options[0].tag, messages.installedTagNoVersion) assert.deepEqual(picker.initialValues, ['method']) }) +test('reconcileModuleSelection auto-selects required modules and locks them while dependents stay ticked', () => { + const { options } = modulePicker(messages, modules, fresh) + + const addedLoop = reconcileModuleSelection(['toolsmith'], ['toolsmith', 'bmad-loop'], options, messages) + assert.deepEqual(addedLoop.values, ['method', 'toolsmith', 'bmad-loop']) + assert.ok(addedLoop.notice.includes('Auto-selected BMad Method')) + assert.deepEqual(requiredByNames(addedLoop.values, options).get('method'), ['BMad Loop']) + + const triedUntickMethod = reconcileModuleSelection(addedLoop.values, ['toolsmith', 'bmad-loop'], options, messages) + assert.deepEqual(triedUntickMethod.values, ['method', 'toolsmith', 'bmad-loop']) + assert.ok(triedUntickMethod.notice.includes('BMad Method stays selected')) + + const addedBoth = reconcileModuleSelection(addedLoop.values, ['method', 'toolsmith', 'tea', 'bmad-loop'], options, messages) + assert.deepEqual(requiredByNames(addedBoth.values, options).get('method'), ['BMad Test Architect', 'BMad Loop']) + + const untickedLoopOnly = reconcileModuleSelection(addedBoth.values, ['method', 'toolsmith', 'tea'], options, messages) + assert.deepEqual(requiredByNames(untickedLoopOnly.values, options).get('method'), ['BMad Test Architect']) + const stillLockedByTea = reconcileModuleSelection(untickedLoopOnly.values, ['toolsmith', 'tea'], options, messages) + assert.deepEqual(stillLockedByTea.values, ['method', 'toolsmith', 'tea']) + assert.ok(stillLockedByTea.notice.includes('BMad Test Architect')) + + const untickedLoop = reconcileModuleSelection(triedUntickMethod.values, ['method', 'toolsmith'], options, messages) + assert.deepEqual(untickedLoop.values, ['method', 'toolsmith']) + assert.equal(untickedLoop.notice, '') + assert.equal(requiredByNames(untickedLoop.values, options).get('method'), undefined) + + const clearedAll = reconcileModuleSelection(['method', 'toolsmith', 'bmad-loop'], [], options, messages) + assert.deepEqual(clearedAll.values, []) + assert.equal(clearedAll.notice, '') + + // L5: inverting from [method, toolsmith] to [tea, bmad-loop, creative, founder] names both TEA and Loop as triggers. + const inverted = reconcileModuleSelection(['method', 'toolsmith'], ['tea', 'bmad-loop', 'creative', 'founder'], options, messages) + assert.deepEqual(inverted.values, ['method', 'tea', 'bmad-loop', 'creative', 'founder']) + assert.ok(inverted.notice.includes('BMad Test Architect, BMad Loop'), inverted.notice) + + // L4: a hidden/always module in requires is ignored so it never triggers a phantom notice. + const withAlwaysDep = options.map((opt) => (opt.value === 'founder' ? { ...opt, requires: ['core-tools'] } : opt)) + const pickedFounder = reconcileModuleSelection([], ['founder'], withAlwaysDep, messages) + assert.deepEqual(pickedFounder.values, ['founder']) + assert.equal(pickedFounder.notice, '') +}) + +test('a TEA-only existing install pre-ticks BMad Method and records the initial notice', () => { + const picker = modulePicker(messages, modules, { + installedCodes: ['core-tools', 'tea'], + installedVersions: { tea: '4.6.2' }, + }) + assert.deepEqual(picker.initialValues, ['method', 'tea']) + assert.ok(picker.initialNotice.includes('Auto-selected BMad Method')) + assert.ok(picker.initialNotice.includes('BMad Test Architect')) +}) + test('the agent picker lists every agent by name, preselected first, then alphabetically', async () => { const agents = await loadAgents() const picker = agentPicker(agents, { initial: ['cursor', 'augment'] }) @@ -74,3 +141,207 @@ test('a project holding the old suite has Creative ticked', () => { const picker = modulePicker(messages, modules, { installedCodes: ['core-tools', 'cis'], installedVersions: { cis: '0.4.0' } }) assert.deepEqual(picker.initialValues, ['creative']) }) + +/** @param {number} columns */ +function renderIntro(columns) { + const out = /** @type {PassThrough & { columns?: number }} */ (new PassThrough()) + out.columns = columns + let raw = '' + out.on('data', (chunk) => { + raw += chunk.toString() + }) + showIntro(messages, out) + return stripVTControlCharacters(raw) +} + +test('showIntro renders the wide lockup with symmetric padding and the V7 pill', () => { + const rendered = renderIntro(120) + const lines = rendered.trimEnd().split('\n') + const boxLines = lines.slice(0, -1) + const pillLine = lines.at(-1) ?? '' + + assert.equal([...boxLines[0]].length, 116) + for (const line of boxLines) { + assert.equal([...line].length, 116) + } + + // Row 3 (rows[1]) is the first mark + wordmark row: 3 outer spaces + 1 tile margin = 4 leading spaces, and 3 trailing spaces after the 80-col wordmark. + const firstLogoInner = [...boxLines[3]].slice(1, -1).join('') + assert.equal((firstLogoInner.match(/^ */)?.[0] ?? '').length, 4) + assert.equal((firstLogoInner.match(/ *$/)?.[0] ?? '').length, 3) + + assert.ok(rendered.includes(messages.eyebrow)) + for (const line of messages.intro.split('\n')) assert.ok(rendered.includes(line)) + assert.ok(rendered.includes(messages.credit)) + assert.ok(pillLine.includes('BMad Installer V7')) +}) + +test('showIntro renders the 78-column stacked BMad / Method box on an 80-column terminal', () => { + const rendered = renderIntro(80) + const lines = rendered.trimEnd().split('\n') + const boxLines = lines.slice(0, -1) + const pillLine = lines.at(-1) ?? '' + + assert.equal([...boxLines[0]].length, 78) + for (const line of boxLines) { + assert.equal([...line].length, 78) + } + + // Row 8 is the first Method row (24-col tile + 2-col gap + 46-col Method = 72 cols): 2 outer spaces + 1 tile margin = 3 left, 2 right. + const methodInner = [...boxLines[8]].slice(1, -1).join('') + assert.equal((methodInner.match(/^ */)?.[0] ?? '').length, 3) + assert.equal((methodInner.match(/ *$/)?.[0] ?? '').length, 2) + + assert.ok(rendered.includes(messages.eyebrow)) + for (const line of messages.intro.split('\n')) assert.ok(rendered.includes(line)) + assert.ok(rendered.includes(messages.credit)) + assert.ok(pillLine.includes('BMad Installer V7')) +}) + +test('showIntro falls back to the guide-rail intro below 78 columns and wraps within the terminal width', () => { + const rendered = renderIntro(60) + assert.equal(rendered.includes('████████▄'), false) + assert.ok(rendered.includes('BMad Installer V7')) + assert.ok(rendered.includes('BMad Agent as Chief of Staff')) + assert.ok(rendered.includes('https://docs.bmad-method.org')) + for (const line of rendered.trimEnd().split('\n')) { + assert.ok([...line].length <= 60, `line exceeds 60 cols (${[...line].length}): ${line}`) + } +}) + +test('showIntro switches cleanly at the 77/78 and 115/116 column boundaries', () => { + assert.equal(renderIntro(77).includes('████████▄'), false) + const at78 = renderIntro(78).trimEnd().split('\n') + assert.equal([...at78[0]].length, 78) + + const at115 = renderIntro(115).trimEnd().split('\n') + assert.equal([...at115[0]].length, 78) + const at116 = renderIntro(116).trimEnd().split('\n') + assert.equal([...at116[0]].length, 116) +}) + +/** @template T @param {() => T} fn @returns {T} */ +function withoutColorEnv(fn) { + const saved = { + FORCE_COLOR: process.env.FORCE_COLOR, + NO_COLOR: process.env.NO_COLOR, + NODE_DISABLE_COLORS: process.env.NODE_DISABLE_COLORS, + COLORTERM: process.env.COLORTERM, + } + delete process.env.FORCE_COLOR + delete process.env.NO_COLOR + delete process.env.NODE_DISABLE_COLORS + delete process.env.COLORTERM + try { + return fn() + } finally { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k] + else process.env[k] = v + } + } +} + +test('colorLevel and showIntro adapt across none, 16-colour ANSI, and 24-bit truecolor streams', () => withoutColorEnv(() => { + const plain = /** @type {PassThrough & { columns?: number }} */ (new PassThrough()) + plain.columns = 120 + let plainRaw = '' + plain.on('data', (c) => { plainRaw += c.toString() }) + assert.equal(colorLevel(plain), 'none') + showIntro(messages, plain) + assert.equal(plainRaw.includes('38;2;'), false) + + const ansi16 = /** @type {PassThrough & { columns?: number, hasColors?: (count?: number) => boolean }} */ (new PassThrough()) + ansi16.columns = 120 + ansi16.hasColors = (count) => !count || count <= 16 + let ansiRaw = '' + ansi16.on('data', (c) => { ansiRaw += c.toString() }) + assert.equal(colorLevel(ansi16), 'ansi') + showIntro(messages, ansi16) + assert.equal(ansiRaw.includes('38;2;'), false) + assert.ok(ansiRaw.includes('\x1b[44m')) + + const truecolor = /** @type {PassThrough & { columns?: number, hasColors?: (count?: number) => boolean }} */ (new PassThrough()) + truecolor.columns = 120 + truecolor.hasColors = () => true + let tcRaw = '' + truecolor.on('data', (c) => { tcRaw += c.toString() }) + assert.equal(colorLevel(truecolor), 'truecolor') + showIntro(messages, truecolor) + assert.ok(tcRaw.includes('48;2;29;55;122')) + assert.ok(tcRaw.includes('38;2;147;180;255')) +})) + +test('showNote keeps ordinary notes unstyled and highlights only the post-blank block when asked', () => withoutColorEnv(() => { + const outPlain = /** @type {PassThrough & { columns?: number, hasColors?: () => boolean }} */ (new PassThrough()) + outPlain.columns = 100 + outPlain.hasColors = () => true + let normalRaw = '' + outPlain.on('data', (c) => { normalRaw += c.toString() }) + showNote('Everything is set up.\nBMad Method 7.0.0', 'BMad install', { output: outPlain }) + assert.equal(normalRaw.includes('\x1b[2mEverything is set up.'), false) + assert.equal(normalRaw.includes('38;2;147;180;255'), false) + + const outSummary = /** @type {PassThrough & { columns?: number, hasColors?: () => boolean }} */ (new PassThrough()) + outSummary.columns = 100 + outSummary.hasColors = () => true + let summaryRaw = '' + outSummary.on('data', (c) => { summaryRaw += c.toString() }) + showNote('Project /demo\nModules Method\n\nNext Start agent', 'BMad is installed', { accentAfterBlank: true, output: outSummary }) + assert.equal(summaryRaw.includes('38;2;147;180;255mProject'), false) + assert.ok(summaryRaw.includes('38;2;147;180;255mNext Start agent')) +})) + +test('chooseModules shows a plain-text cursor, does not wrap early with colour, and enforces live dependencies', async () => { + const input = new PassThrough() + const output = /** @type {PassThrough & { columns?: number, hasColors?: () => boolean }} */ (new PassThrough()) + output.columns = 105 + /** @type {string[]} */ + const frames = [] + output.on('data', (chunk) => frames.push(chunk.toString())) + + const pending = chooseModules(messages, modules, fresh, { input, output }) + await new Promise((r) => setImmediate(r)) + const firstFrame = stripVTControlCharacters(frames.join('')) + assert.match(firstFrame, /[›>] [◼◻+] BMad Method/) + assert.match(firstFrame, / [◼◻+] BMad Toolsmith/) + + // Untick Method (space), move down 3 rows to BMad Loop, tick Loop (space) -> Method auto-ticks! + input.write(' ') + input.write('\x1b[B\x1b[B\x1b[B') + const beforeLoop = frames.length + input.write(' ') + await new Promise((r) => setImmediate(r)) + const afterLoopFrame = stripVTControlCharacters(frames.slice(beforeLoop).join('')) + assert.ok(afterLoopFrame.includes('Auto-selected BMad Method')) + assert.match(afterLoopFrame, /[›>] [◼+] BMad Loop/) + + input.write('\r') + const picked = await pending + assert.deepEqual(picked, ['method', 'toolsmith', 'bmad-loop']) + + // With colour enabled at 105 cols, none of the 6 module rows prematurely wrap onto an unindented continuation line. + const colorInput = new PassThrough() + const colorOut = /** @type {PassThrough & { columns?: number, hasColors?: () => boolean }} */ (new PassThrough()) + colorOut.columns = 105 + colorOut.hasColors = () => true + let colorBuf = '' + colorOut.on('data', (c) => { colorBuf += c.toString() }) + const colorPending = chooseModules(messages, modules, fresh, { input: colorInput, output: colorOut }) + await new Promise((r) => setImmediate(r)) + const strippedLines = stripVTControlCharacters(colorBuf).split('\n') + const toolsmithLine = strippedLines.find((line) => line.includes('BMad Toolsmith')) ?? '' + assert.ok(toolsmithLine.includes('with evals'), `Toolsmith wrapped early at 105 cols: ${toolsmithLine}`) + // Press 'a' twice to select all then clear all, then Enter -> [] + colorInput.write('aa\r') + assert.deepEqual(await colorPending, []) + + // Esc cancels with Cancelled + const escInput = new PassThrough() + const escOut = /** @type {PassThrough & { columns?: number }} */ (new PassThrough()) + escOut.columns = 105 + const escPending = chooseModules(messages, modules, fresh, { input: escInput, output: escOut }) + await new Promise((r) => setImmediate(r)) + escInput.write('\x1b') + await assert.rejects(escPending, Cancelled) +})