import fs from 'node:fs'; import path from 'node:path'; import { intro, outro, log } from '@clack/prompts'; import { promptFeatures } from './prompt.js'; import { resolveResourceTargets, readManifest, saveManifest, reconcileSlots, } from './injection-core.js'; import { isPluginDetected } from './plugins.js'; import { resolveSelected } from './providers.js'; /** * Emit an actionable, loud warning when an anchor cannot be located (the user * rewrote the adjacent prose, or the sidecar drifted). Never a silent no-op. * @param {string} namespace * @param {string} name * @param {string} resourceName * @param {Array<{sections:string[], anchor:object}>} missed */ function logSlotWarnings(warnings) { for (const w of warnings || []) log.warn(`${w.resource} slot ${w.slot} member ${w.member}: ${w.reason}`); } function reconcileFeatureSlots(cwd) { const result = reconcileSlots(cwd, { pluginActive: isPluginDetected }); if (!result) { log.warn('Feature prompts were not updated: this installation has no v2 injection sidecar. Run `codeadd update`.'); return { modified: [], warnings: [] }; } logSlotWarnings(result.warnings); return result; } function setFeatureFlag(cwd, featureName, enabled) { const manifest = readManifest(cwd); if (!manifest) return; if (!manifest.features) manifest.features = {}; manifest.features[featureName] = enabled; manifest.features = normalizeFeatureStates(manifest.features).states; saveManifest(cwd, manifest); } /** * Feature registry — each optional feature that can be toggled. * * The key doubles as the fragment directory name (see getFragments), so a key * rename is also a directory rename. `aliases` carries retired keys so a * manifest written before the rename still resolves to the user's choice * instead of silently falling back to `default`. */ /** Feature keys that no longer exist. A manifest that still carries one loses it on load. */ const RETIRED_FEATURES = ['board']; export const FEATURES = { 'tdd-pipeline': { description: 'TDD pipeline (test-first ordering + unit/integration generation)', default: true, aliases: ['tdd'], commands: ['add-plan', 'add-build', 'add-review', 'add-hotfix'], }, 'qa-pipeline': { description: 'QA pipeline (E2E authoring + agent QA validation)', default: false, // add-review joined in 2026-09-13T153219-PLAN--test-terminal-states-and-qa-feature-boundary. // The judgement steps used to sit in add-review's ungated base body and // self-gate on the /add-qa-setup receipt alone. Their INPUT is authored by // @e2e-agent, which this feature already gates — so with the feature off // the judges read an empty directory and every in-contract screen became a // coverage blocker. Gating them here is what makes the flag mean one thing // for the whole QA flow. commands: ['add-plan', 'add-build', 'add-review'], }, // OFF by default, and that is the decision, not an oversight: this one // DELETES the user's documentation, which is their call to make. It also // refuses to run at all unless /add-done wrote a delivery index entry in the // same run — pruning the scaffolding before the record exists inverts the // whole design. 'docs-pruning': { description: 'Prune post-merge feature scaffolding (discovery, tasks, epic, reviews) after the delivery index entry is written', default: false, commands: ['add-done'], }, // OFF by default because it changes how a command TALKS, and a person at a // terminal is who the commands were written for. On, the human-only passages // (one question per turn, the structured-question tool, the yes/no // continuation offer, confirming stops that wait) are swapped for bot ones // through the agent-mode.* slots, and every command loads // add--agent-interaction instead of add--human-interaction. Off, the slot // fallbacks hold today's text. `commands` lists the commands whose slots and // fragment have landed; the plan (0038B) ends it at the twelve of its design, // the 0038B brainstorm design. 'agent-mode': { description: 'Agent mode (commands ask in one numbered batch with a recommendation, call no interactive tool, and close on the next command) for bots that drive them headless', default: false, commands: ['add-brainstorm', 'add-new', 'add-plan', 'add-build', 'add-review', 'add-done', 'add-diagnose', 'add-hotfix', 'add-qa-setup', 'add-pull-request', 'add-audit', 'add-wiki'], }, }; /** * Resolve a user-supplied feature name to its canonical registry key. * Accepts the canonical key or any retired alias. * @param {string} name * @returns {{ key: string, alias: string|null } | null} */ export function resolveFeatureName(name) { if (FEATURES[name]) return { key: name, alias: null }; for (const [key, meta] of Object.entries(FEATURES)) { if (meta.aliases?.includes(name)) return { key, alias: name }; } return null; } /** * Resolve one feature's enabled state from a manifest's `features` map. * * Order is load-bearing: explicit canonical key, THEN any alias key, THEN * `meta.default`. Reaching the default before consulting aliases is what * silently re-enables a feature the user explicitly disabled under its old key. * * @param {Record} featureStates * @param {string} key canonical registry key * @param {object} meta registry entry * @returns {{ enabled: boolean, legacyKey: string|null }} */ function resolveFeatureState(featureStates, key, meta) { if (Object.prototype.hasOwnProperty.call(featureStates, key)) { return { enabled: featureStates[key], legacyKey: null }; } for (const alias of meta.aliases ?? []) { if (Object.prototype.hasOwnProperty.call(featureStates, alias)) { return { enabled: featureStates[alias], legacyKey: alias }; } } return { enabled: meta.default, legacyKey: null }; } /** * Rewrite a manifest's `features` map with canonical keys, dropping any alias * key that was resolved into one. Pure — returns a new map plus whether the * rewrite changed anything. * * @param {Record} featureStates * @returns {{ states: Record, changed: boolean }} */ export function normalizeFeatureStates(featureStates) { const states = { ...featureStates }; let changed = false; // A retired feature is dropped, not rejected: a manifest written while the feature // existed must still load. Migration 0006-retire-board does the same to the manifest on update. for (const retired of RETIRED_FEATURES) { if (!Object.prototype.hasOwnProperty.call(states, retired)) continue; delete states[retired]; changed = true; } for (const [key, meta] of Object.entries(FEATURES)) { for (const alias of meta.aliases ?? []) { if (!Object.prototype.hasOwnProperty.call(states, alias)) continue; if (!Object.prototype.hasOwnProperty.call(states, key)) { states[key] = states[alias]; } delete states[alias]; changed = true; } } return { states, changed }; } /** * Get fragment files for a feature. * @param {string} cwd * @param {string} featureName * @returns {Array<{commandName: string, content: string}>} */ function getFragments(cwd, featureName) { const fragmentDir = path.join(cwd, '.codeadd', 'fragments', featureName); if (!fs.existsSync(fragmentDir)) return []; const fragments = []; for (const entry of fs.readdirSync(fragmentDir, { withFileTypes: true })) { if (!entry.isFile() || !entry.name.endsWith('.md')) continue; const commandName = entry.name.replace('.md', ''); const content = fs.readFileSync(path.join(fragmentDir, entry.name), 'utf8'); fragments.push({ commandName, content }); } return fragments; } /** * Warn, once, that a feature does nothing on the installed providers that carry no * `commandsSubdir` (Codex, Antigravity, ZCode install commands as skills, and * injection only targets commands). Reads the manifest at call time, so a caller * that changed providers first sees the final set. Silent when none is installed. * Never changes the manifest, an exit code or what enabling does. * @param {string} cwd * @param {string} featureKey canonical registry key, never a retired alias */ export function warnUninjectedProviders(cwd, featureKey) { const manifest = readManifest(cwd); const labels = resolveSelected(manifest?.providers ?? [], manifest?.scope ?? 'project') .filter((p) => !p.commandsSubdir) .map((p) => p.label); if (labels.length === 0) return; log.warn(`Feature "${featureKey}" has no effect on ${labels.join(', ')}: they install commands as skills and receive no feature injection.`); } /** * Enable a feature — inject fragment content into command markers. * @param {string} cwd * @param {string} featureName * @returns {{modified: number}} */ export function enableFeature(cwd, featureName) { setFeatureFlag(cwd, featureName, true); const result = reconcileFeatureSlots(cwd); return { modified: result.modified.length }; } /** * Disable a feature — remove content between command markers. * @param {string} cwd * @param {string} featureName * @returns {{modified: number}} */ export function disableFeature(cwd, featureName) { setFeatureFlag(cwd, featureName, false); const result = reconcileFeatureSlots(cwd); return { modified: result.modified.length }; } /** * Apply all enabled features after install/update. * @param {string} cwd */ export function applyEnabledFeatures(cwd) { const manifest = readManifest(cwd); if (!manifest) return; const featureStates = { ...(manifest.features ?? {}) }; for (const [name, meta] of Object.entries(FEATURES)) { const { enabled } = resolveFeatureState(featureStates, name, meta); featureStates[name] = enabled; } manifest.features = normalizeFeatureStates(featureStates).states; saveManifest(cwd, manifest); const result = reconcileFeatureSlots(cwd); return result.modified.length; } /** * Get current feature states. * @param {string} cwd * @returns {Array<{name: string, description: string, enabled: boolean}>} */ export function getFeatureStates(cwd) { const manifest = readManifest(cwd); const featureStates = manifest?.features ?? {}; return Object.entries(FEATURES).map(([name, meta]) => { const { enabled, legacyKey } = resolveFeatureState(featureStates, name, meta); return { name, description: meta.description, enabled, legacyKey }; }); } /** * CLI entry point for `codeadd features` subcommand. * Scope flows through manifest.scope (read by resolveResourceTargets); the param * exists so bin can pass it positionally and is the fallback when absent. * @param {string} cwd * @param {string[]} args * @param {'project'|'global'} [scope] */ export async function features(cwd, args, scope = 'project') { void scope; const action = args[0]; const featureName = args[1]; if (!action || action === 'list') { intro('ADD CLI - Features'); const states = getFeatureStates(cwd); const currentlyEnabled = states.filter((f) => f.enabled).map((f) => f.name); for (const { name, legacyKey } of states) { if (legacyKey) { log.warn(`Manifest still carries the retired key "${legacyKey}". It resolves to "${name}" and is normalised on the next update.`); } } // Nobody to answer the multiselect: print the states and stop, as `plugins list` does. if (!process.stdin.isTTY) { log.message(states.map((f) => `${f.enabled ? '●' : '○'} ${f.name} — ${f.description}`).join('\n')); outro('Change with: codeadd features enable|disable '); return; } const selected = await promptFeatures(currentlyEnabled); let totalModified = 0; for (const { name } of states) { const wasEnabled = currentlyEnabled.includes(name); const nowEnabled = selected.includes(name); if (nowEnabled && !wasEnabled) { const { modified } = enableFeature(cwd, name); totalModified += modified; log.success(`Feature "${name}" enabled. ${modified} file(s) modified.`); warnUninjectedProviders(cwd, name); } else if (!nowEnabled && wasEnabled) { const { modified } = disableFeature(cwd, name); totalModified += modified; log.success(`Feature "${name}" disabled. ${modified} file(s) modified.`); } } if (totalModified === 0) { log.info('No changes.'); } outro('Done.'); return; } if (action === 'enable' || action === 'disable') { if (!featureName) { outro(`ERROR: Missing feature name. Usage: codeadd features ${action} `); process.exit(1); } const resolved = resolveFeatureName(featureName); if (!resolved) { outro(`ERROR: Unknown feature "${featureName}". Available: ${Object.keys(FEATURES).join(', ')}`); process.exit(1); } intro(`ADD CLI - Features ${action}`); // An alias is honoured, never rejected: somebody's setup script calls // `features disable tdd`, and failing it turns a rename into an outage. if (resolved.alias) { log.warn(`"${resolved.alias}" is deprecated and now means "${resolved.key}". Update your scripts.`); } const canonical = resolved.key; if (action === 'enable') { const { modified } = enableFeature(cwd, canonical); log.success(`Feature "${canonical}" enabled. ${modified} file(s) modified.`); warnUninjectedProviders(cwd, canonical); } else { const { modified } = disableFeature(cwd, canonical); log.success(`Feature "${canonical}" disabled. ${modified} file(s) modified.`); } outro('Done.'); return; } log.error(`Unknown action "${action}". Use: list, enable, disable`); process.exit(1); }