import fs from 'node:fs'; import path from 'node:path'; import AdmZip from 'adm-zip'; import { intro, outro, log } from '@clack/prompts'; import { PROVIDERS, resolveSelected, exclusiveFiles, ownedRoots, globalCapable } from './providers.js'; import { copyRelease, pruneObsolete, shouldPreserve } from './release-copy.js'; import { downloadReleaseAsset } from './github.js'; import { fixLineEndings, writeManifest, reportMcpRegistration, reportNotDetectedPlugins } from './installer.js'; import { readManifest, saveManifest, captureBaselines, loadInjectionSidecar } from './injection-core.js'; import { FEATURES, resolveFeatureName, normalizeFeatureStates, applyEnabledFeatures, enableFeature, disableFeature, getFeatureStates, warnUninjectedProviders, } from './features.js'; import { loadCatalog, enablePlugin, disablePlugin, applyEnabledPluginsDetailed, removePluginSkillsFor, getPluginStates, } from './plugins.js'; import { writeMcpRegistration, unregisterProvider } from './mcp-registration.js'; import { getInstalledDirs, writeGitignoreBlock } from './gitignore.js'; import { promptConfirm, promptModify, promptApplyDiff } from './prompt.js'; import { readChangeFlags } from './change-flags.js'; /** * The core every way of changing an installation goes through. * * `desired` is `{ providers?: string[], features?: {name: boolean}, plugins?: {name: boolean} }`. * A key left out means "unchanged", so a caller states only what it wants to move. * `diffState` compares it with the manifest and `applyDesiredState` applies only * the difference. Nothing else in the CLI re-implements this, so the doors on top * of it (`providers`, `modify`, the install menu) cannot drift apart. * * THE ORDER INSIDE THE ADD PATH IS A CONSTRAINT, NOT A DETAIL: * copy -> prune -> write manifest -> captureBaselines -> features -> plugins -> * MCP -> .gitignore. `captureBaselines` and both apply functions resolve their * targets from the manifest's providers, so the manifest must already carry the * new set when they run. And the recopy covers EVERY desired provider, not just * the new one: `captureBaselines` snapshots whatever is on disk, so a provider * left composed would be baselined as pristine and injected twice. */ const BASELINE_ROOT = '.codeadd/baselines'; /** * Manifest fields `writeManifest` sets itself; every other field travels through an add verbatim. * `installedAt` is deliberately NOT here: it means the first install and an add keeps it. */ const SET_BY_WRITE = new Set(['version', 'releaseTag', 'providers', 'files', 'hashes', 'baselineHashes']); function currentFeature(manifest, name) { const states = normalizeFeatureStates(manifest.features ?? {}).states; return states[name] ?? FEATURES[name]?.default ?? false; } function currentPlugin(manifest, name) { return manifest.plugins?.[name]?.enabled === true; } /** * What would change if `desired` were applied to this manifest. * * @param {object} manifest * @param {{providers?: string[], features?: Record, plugins?: Record}} desired * @returns {{ * providers: {add: string[], remove: string[]}, * features: {enable: string[], disable: string[]}, * plugins: {enable: string[], disable: string[]}, * isEmpty: boolean * }} */ export function diffState(manifest, desired) { const current = manifest.providers ?? []; const wanted = desired.providers ?? current; const toggles = (wantedStates = {}, isOn) => { const entries = Object.entries(wantedStates); return { enable: entries.filter(([name, on]) => on && !isOn(name)).map(([name]) => name), disable: entries.filter(([name, on]) => !on && isOn(name)).map(([name]) => name), }; }; const diff = { providers: { add: wanted.filter((key) => !current.includes(key)), remove: current.filter((key) => !wanted.includes(key)), }, features: toggles(desired.features, (name) => currentFeature(manifest, name)), plugins: toggles(desired.plugins, (name) => currentPlugin(manifest, name)), }; diff.isEmpty = [ diff.providers.add, diff.providers.remove, diff.features.enable, diff.features.disable, diff.plugins.enable, diff.plugins.disable, ].every((list) => list.length === 0); return diff; } /** * Refuse a request that cannot be applied, BEFORE anything is touched. Returns * `desired` with feature names resolved to their canonical keys. * * Exported so `install` can refuse a bad name before it downloads anything, * with the same wording `modify` uses. */ export function validateDesired(desired, scope, installed = []) { // Only providers being ADDED are checked: one the CLI no longer knows (an old // install's `gemini`) may stay installed or be removed, but never be added. for (const key of (desired.providers ?? []).filter((k) => !installed.includes(k))) { if (!PROVIDERS[key]) { throw new Error(`Unknown provider "${key}". Available: ${Object.keys(PROVIDERS).join(', ')}`); } if (scope === 'global' && !globalCapable(key)) { throw new Error(`Provider "${key}" cannot be installed globally: it has no user-level destination.`); } } const features = {}; for (const [name, on] of Object.entries(desired.features ?? {})) { const resolved = resolveFeatureName(name); if (!resolved) throw new Error(`Unknown feature "${name}". Available: ${Object.keys(FEATURES).join(', ')}`); // An alias and its canonical key are one feature: asking for opposite states is a conflict, // and the flag reader cannot see it because it compares the raw names. if (resolved.key in features && features[resolved.key] !== on) { throw new Error(`"${name}" and "${resolved.key}" are the same feature and were asked for opposite states. Pick one.`); } if (resolved.alias) log.warn(`"${resolved.alias}" is deprecated and now means "${resolved.key}". Update your scripts.`); features[resolved.key] = on; } const catalog = loadCatalog(); for (const name of Object.keys(desired.plugins ?? {})) { if (!catalog[name]) { throw new Error(`Unknown plugin "${name}". Available: ${Object.keys(catalog).join(', ') || 'none'}`); } } return { ...desired, features }; } /** Delete empty directories under `root`, bottom-up, then `root` itself if it ends up empty. */ function pruneEmptyDirs(root) { if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) return; for (const entry of fs.readdirSync(root, { withFileTypes: true })) { if (entry.isDirectory()) pruneEmptyDirs(path.join(root, entry.name)); } if (fs.readdirSync(root).length === 0) fs.rmdirSync(root); } /** * Tidy the roots of providers that were removed, except the ones a remaining * provider still owns (codex and zcode share `.agents`). */ function pruneRemovedRoots(targetDir, removedEntries, remainingEntries) { const kept = new Set(remainingEntries.flatMap(ownedRoots)); for (const root of removedEntries.flatMap(ownedRoots)) { if (!kept.has(root)) pruneEmptyDirs(path.join(targetDir, root)); } } function removeBaselineDirs(targetDir, removedKeys) { for (const key of removedKeys) { fs.rmSync(path.join(targetDir, BASELINE_ROOT, key), { recursive: true, force: true }); } } /** Report what the unregister did — the same voice `reportMcpRegistration` uses. */ function reportMcpRemoval(results) { const removed = results.filter((r) => r.status === 'removed').length; if (removed > 0) log.success(`Knowledge-graph MCP unregistered for ${removed} provider(s).`); for (const r of results) { if (r.status === 'print') { log.info(`${r.provider}: ${r.line}`); } else if (r.status === 'unreadable') { log.warn(`${r.provider}: ${r.file} could not be read and was left untouched — ${r.line}`); } } } function syncGitignore(targetDir, manifest, scope, providerKeys) { // Project scope only, and only when the install opted in — the rule `update` applies. if (scope === 'project' && manifest.gitignore === true) { writeGitignoreBlock(targetDir, getInstalledDirs(providerKeys)); log.success('.gitignore synced.'); } } /** * A provider was added (with or without removals in the same change): recopy * `.codeadd/` and EVERY desired provider from the release the installation is * already on, then rebuild everything that depends on pristine files. */ async function applyAdd(targetDir, manifest, scope, wanted, diff) { const tag = manifest.releaseTag ?? `v${manifest.version}`; const wantedEntries = resolveSelected(wanted.providers, scope); const removedEntries = resolveSelected(diff.providers.remove, scope); const addedEntries = resolveSelected(diff.providers.add, scope); // Refuse BEFORE the download: on a v1 sidecar the re-apply below is a no-op and the // recopy would strip every feature and plugin injection from the providers. if (loadInjectionSidecar(targetDir)?.version !== 2) { throw new Error('Adding a provider needs v2 injection data. Run `codeadd update` first.'); } // Download FIRST. A tag that no longer downloads must leave every file as it was. let buffer; try { buffer = await downloadReleaseAsset(tag); } catch (err) { throw new Error( `Could not download the installed release ${tag}: ${err.message}. Nothing was changed. ` + 'Run `codeadd update` to move to a release that can be downloaded.', ); } const copied = copyRelease(new AdmZip(buffer), targetDir, wantedEntries, { skipPreserved: true }); // Files of an installed provider this CLI does not know are neither rewritten nor // pruned, and stay tracked: they sit outside `.codeadd/` and every known provider root. const knownRoots = resolveSelected(Object.keys(PROVIDERS), scope).flatMap(ownedRoots); const foreign = (manifest.files ?? []).filter( (f) => !f.startsWith('.codeadd/') && !knownRoots.some((r) => f === r || f.startsWith(`${r}/`)), ); const written = [...copied, ...foreign.filter((f) => !copied.includes(f))]; fixLineEndings(path.join(targetDir, '.codeadd', 'scripts')); const pruned = pruneObsolete(targetDir, manifest.files ?? [], written); if (pruned > 0) log.success(`Removed ${pruned} obsolete file(s).`); removePluginSkillsFor(targetDir, removedEntries, wantedEntries); removeBaselineDirs(targetDir, diff.providers.remove); pruneRemovedRoots(targetDir, removedEntries, wantedEntries); // Everything the manifest carried that writeManifest does not set itself travels // through verbatim; `baselineHashes` is rebuilt by captureBaselines just below and `installedAt` is kept. const carried = Object.fromEntries(Object.entries(manifest).filter(([key]) => !SET_BY_WRITE.has(key))); writeManifest(targetDir, manifest.version, wanted.providers, written, manifest.releaseTag ?? tag, carried); const baselines = captureBaselines(targetDir); for (const w of baselines.warnings) log.warn(`${w.resource} ${w.slot} ${w.member}: ${w.reason}`); const features = applyEnabledFeatures(targetDir); if (features > 0) log.success(`Re-applied ${features} feature injection(s).`); const plugins = applyEnabledPluginsDetailed(targetDir); if (plugins.modified > 0) log.success(`Re-applied ${plugins.modified} plugin injection(s).`); reportNotDetectedPlugins(plugins.notDetected); if (addedEntries.length > 0) reportMcpRegistration(writeMcpRegistration(targetDir, addedEntries, manifest.version)); if (diff.providers.remove.length > 0) { reportMcpRemoval(diff.providers.remove.map((key) => unregisterProvider(targetDir, key))); } } /** * Providers were only removed: no download, and NO `captureBaselines`. The * remaining providers' files are already composed, so snapshotting them now * would record composed text as pristine and the next composition would inject * twice. The manifest is edited in place rather than rewritten, because * `writeManifest` would drop `baselineHashes` and reset `installedAt`. */ function applyRemove(targetDir, manifest, scope, wanted, diff) { const removedEntries = resolveSelected(diff.providers.remove, scope); const remainingEntries = resolveSelected(wanted.providers, scope); const files = manifest.files ?? []; // exclusiveFiles reads the manifest list, so nothing outside it is ever deleted; // shouldPreserve is the one definition of "never delete this" on top of that. const owned = exclusiveFiles(files, removedEntries, remainingEntries); for (const file of owned.filter((f) => !shouldPreserve(f))) { try { fs.rmSync(path.join(targetDir, file), { force: true }); } catch { // A file that cannot be removed is not worth failing the change over. } } // What leaves the manifest: everything the removed provider owned, EXCEPT a file // that is still on disk only because it could not be deleted — that one stays // tracked. A preserved file stays on disk but is no longer ours to track. const doomed = new Set( owned.filter((f) => shouldPreserve(f) || !fs.existsSync(path.join(targetDir, f))), ); removePluginSkillsFor(targetDir, removedEntries, remainingEntries); removeBaselineDirs(targetDir, diff.providers.remove); pruneRemovedRoots(targetDir, removedEntries, remainingEntries); const prefixes = diff.providers.remove.map((key) => `${BASELINE_ROOT}/${key}/`); const next = { ...manifest, providers: wanted.providers }; next.files = files.filter((f) => !doomed.has(f)); next.hashes = Object.fromEntries(Object.entries(manifest.hashes ?? {}).filter(([f]) => !doomed.has(f))); if (manifest.baselineHashes) { next.baselineHashes = Object.fromEntries( Object.entries(manifest.baselineHashes).filter(([f]) => !prefixes.some((p) => f.startsWith(p))), ); } saveManifest(targetDir, next); reportMcpRemoval(diff.providers.remove.map((key) => unregisterProvider(targetDir, key))); } /** * Apply `desired` to the installation under `targetDir`. * * @param {string} targetDir the scope-resolved install root * @param {{providers?: string[], features?: Record, plugins?: Record}} desired * @param {{force?: boolean}} [options] `force` skips the removal confirmation * @returns {Promise & {pluginsNotEnabled: string[]}>} * what was applied, plus the plugins asked for whose tool was not detected. A caller * without a person to read the warning turns that list into a failing exit. */ export async function applyDesiredState(targetDir, desired, { force = false } = {}) { const manifest = readManifest(targetDir); if (!manifest) throw new Error('No ADD installation found. Run `npx codeadd install` first.'); const scope = manifest.scope ?? 'project'; const installed = manifest.providers ?? []; const checked = validateDesired(desired, scope, installed); // Installed providers keep their manifest order; new ones follow in the order asked. // A prompt hands back its own display order, which must not reshuffle the manifest. const asked = checked.providers ?? installed; const wanted = { ...checked, providers: [...installed.filter((key) => asked.includes(key)), ...asked.filter((key) => !installed.includes(key))], }; const diff = diffState(manifest, wanted); if (diff.isEmpty) { log.info('Nothing to change.'); return { ...diff, pluginsNotEnabled: [] }; } if (diff.providers.remove.length > 0) { if (!force) { // Nobody to ask: a plain Error exits 1. USER_CANCEL (below) exits 0, which a bot reads as "done". if (!process.stdin.isTTY) { throw new Error( `Removing ${diff.providers.remove.join(', ')} deletes its files from this project, and there is no terminal to ask. Pass --force to confirm.`, ); } // promptConfirm throws USER_CANCEL on a decline, which `runCli` already treats as a clean exit. await promptConfirm(`Remove ${diff.providers.remove.join(', ')}? Its files are deleted from this project.`); } if (wanted.providers.length === 0) { log.warn('No providers left: only .codeadd/ remains.'); } } if (diff.providers.add.length > 0) { await applyAdd(targetDir, manifest, scope, wanted, diff); } else if (diff.providers.remove.length > 0) { applyRemove(targetDir, manifest, scope, wanted, diff); } // Feature and plugin toggles run AFTER the provider change, through the same // functions the `features` and `plugins` subcommands call. for (const name of diff.features.enable) { enableFeature(targetDir, name); warnUninjectedProviders(targetDir, name); } for (const name of diff.features.disable) disableFeature(targetDir, name); const pluginsNotEnabled = []; for (const name of diff.plugins.enable) { const result = enablePlugin(targetDir, name); if (!result.ok) { pluginsNotEnabled.push(name); const entry = loadCatalog()[name]; log.warn(`plugin ${name} was not enabled: its tool was not detected.${entry?.installHint ? ` ${entry.installHint}` : ''}`); } } for (const name of diff.plugins.disable) disablePlugin(targetDir, name); if (diff.providers.add.length > 0 || diff.providers.remove.length > 0) { syncGitignore(targetDir, manifest, scope, wanted.providers); } return { ...diff, pluginsNotEnabled }; } // --------------------------------------------------------------------------- // The two doors. Both end in applyDesiredState; neither re-implements it. // --------------------------------------------------------------------------- const NO_INSTALL = 'No ADD installation found. Run `npx codeadd install` first.'; function requireManifest(cwd) { const manifest = readManifest(cwd); if (!manifest) throw new Error(NO_INSTALL); return manifest; } /** * CLI entry point for `codeadd providers` — `list`, `add `, `remove [--force]`. * Mirrors the shape of `features` and `plugins`. Scope comes from the manifest; * the parameter is the fallback the other subcommands take too. * * Errors are thrown, not exited on: `runCli` prints them and exits 1, and a * test can read the message without the process going away. * * @param {string} cwd the scope-resolved install root * @param {string[]} args * @param {'project'|'global'} [scope] */ export async function providers(cwd, args, scope = 'project') { const action = args[0] ?? 'list'; const manifest = requireManifest(cwd); const installScope = manifest.scope ?? scope; const installed = manifest.providers ?? []; if (action === 'list') { intro('ADD CLI - Providers'); const offered = Object.keys(PROVIDERS).filter((key) => installScope !== 'global' || globalCapable(key)); log.message( offered .map((key) => `${installed.includes(key) ? '●' : '○'} ${key} — ${PROVIDERS[key].label}`) .join('\n'), ); outro('Change with: codeadd providers add|remove , or codeadd modify'); return; } if (action !== 'add' && action !== 'remove') { throw new Error(`Unknown action "${action}". Use: list, add, remove`); } const name = args[1]; if (!name || name.startsWith('--')) throw new Error(`Usage: codeadd providers ${action} `); // Only an ADD needs a known provider: an installed one the CLI no longer knows can still be removed. if (!PROVIDERS[name] && !(action === 'remove' && installed.includes(name))) { throw new Error(`Unknown provider "${name}". Available: ${Object.keys(PROVIDERS).join(', ')}`); } if (action === 'add') { if (installed.includes(name)) { log.info(`"${name}" is already installed: nothing to change.`); return; } intro('ADD CLI - Providers add'); // Said BEFORE anything is written: an add re-copies every provider from the installed release. log.info('Adding a provider re-copies every provider from the installed release; local edits to provider files are overwritten.'); await applyDesiredState(cwd, { providers: [...installed, name] }); outro(`Provider "${name}" added.`); return; } if (!installed.includes(name)) throw new Error(`Provider "${name}" is not installed.`); intro('ADD CLI - Providers remove'); if (!PROVIDERS[name]) { // No known roots, so nothing can be deleted: the entry just leaves the manifest. saveManifest(cwd, { ...manifest, providers: installed.filter((key) => key !== name) }); log.info(`"${name}" is not a provider this CLI knows: it was dropped from the manifest and no files were deleted.`); outro(`Provider "${name}" removed from the manifest.`); return; } await applyDesiredState(cwd, { providers: installed.filter((key) => key !== name) }, { force: args.includes('--force') }); outro(`Provider "${name}" removed.`); } /** * Turn "a requested plugin was not enabled" into a failing exit, AFTER everything * else was applied. The warning `applyDesiredState` already logs is for a person; * a bot needs the exit code. * * @param {string[]} names `pluginsNotEnabled` from `applyDesiredState` */ export function assertPluginsEnabled(names) { if (names.length > 0) { throw new Error(`Plugin ${names.join(', ')} was not enabled: its tool was not detected. Everything else was applied.`); } } const MODIFY_FLAGS_HELP = 'modify needs an interactive terminal, or flags saying what to change: ' + '--providers (the final set), --enable-feature , --disable-feature , ' + '--enable-plugin , --disable-plugin . Add --force to remove a provider.'; /** * CLI entry point for `codeadd modify`. * * With change flags it builds `desired` from them and applies it, with no prompt: * `--providers` is the FINAL set, the feature and plugin flags are deltas. Without * flags it is the interactive editor. * * The editor asks ONCE: `promptApplyDiff` shows the diff and takes the confirmation, * and the core is then called with `force: true` so a removal is not confirmed a * second time. * * @param {string} cwd the scope-resolved install root * @param {string[]} args * @param {'project'|'global'} [scope] */ export async function modify(cwd, args, scope = 'project') { const manifest = requireManifest(cwd); const installScope = manifest.scope ?? scope; const flags = readChangeFlags(args); if (flags.any) { intro('ADD CLI - Modify'); const desired = {}; if (flags.providers !== undefined) desired.providers = flags.providers; if (Object.keys(flags.features).length > 0) desired.features = flags.features; if (Object.keys(flags.plugins).length > 0) desired.plugins = flags.plugins; const result = await applyDesiredState(cwd, desired, { force: flags.force }); assertPluginsEnabled(result.pluginsNotEnabled); outro('Installation updated.'); return; } // No flags and nobody to answer the editor: say what to pass, never wait. if (!process.stdin.isTTY) throw new Error(MODIFY_FLAGS_HELP); intro('ADD CLI - Modify'); const desired = await promptModify( { providers: manifest.providers ?? [], features: getFeatureStates(cwd), plugins: getPluginStates(cwd), }, installScope, ); const diff = diffState(manifest, desired); if (!(await promptApplyDiff(diff))) { outro('Nothing changed.'); return; } await applyDesiredState(cwd, desired, { force: true }); outro('Installation updated.'); }