compat.mjs 6.57 KB
/**
 * 版本兼容与迁移:把「能不能升、升完要做什么」变成可查询的数据,
 * 而不是靠人肉对比两个目录的 diff。
 *
 * 约定(kernel.json 中的可选字段,缺失即视为无约束,保证老内核可被新 CLI 管理):
 *   version           当前内核版本
 *   minCliVersion     管理该内核所需的最低 CLI 版本
 *   minKernelVersion  允许直接升级到此版本的最低当前内核版本(防止跨大版本跳跃)
 *   migrations[]      { from, to, summary, manual?: string[], breaking?: boolean }
 *
 * 升级日志写到项目根 .venus/upgrade-log.json:
 * 它不属于 .kernel/(不进门禁清单),也不属于 apps/packages(不进业务指纹)。
 * 存在的意义是让「哪些项目升级到了哪个版本、执行了哪些迁移」可被回答。
 */
import fs from 'node:fs';
import path from 'node:path';

const SEMVER = /^v?(\d+)\.(\d+)\.(\d+)/;
const LOG_PATH = '.venus/upgrade-log.json';
const LOG_LIMIT = 50;

/** 解析 x.y.z(允许前导 v 与后续后缀);无法解析返回 null。 */
export function parseVersion(value) {
  if (typeof value !== 'string') return null;
  const m = value.trim().match(SEMVER);
  return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
}

/** 语义版本比较:a < b 返回 -1,相等 0,大于 1;任一不可解析返回 null。 */
export function compareVersion(a, b) {
  const pa = parseVersion(a);
  const pb = parseVersion(b);
  if (!pa || !pb) return null;
  for (let i = 0; i < 3; i += 1) {
    if (pa[i] !== pb[i]) return pa[i] < pb[i] ? -1 : 1;
  }
  return 0;
}

/** 取出版本区间与本次升级跨度相交的迁移项,按目标版本排序。 */
export function migrationsBetween(migrations, from, to) {
  if (!Array.isArray(migrations)) return [];
  const lo = compareVersion(from, to);
  if (lo === null || lo >= 0) return [];
  return migrations
    .filter((m) => {
      if (!m || typeof m !== 'object') return false;
      const startsBefore = !m.from || compareVersion(m.from, to) < 0;
      const endsAfter = !m.to || compareVersion(m.to, from) > 0;
      return startsBefore && endsAfter;
    })
    .sort((a, b) => {
      const c = compareVersion(a.to, b.to);
      return c === null ? 0 : c;
    });
}

/**
 * 升级前兼容性判定。不读文件、不产生副作用,方便被 CLI 与升级器共用。
 * @param {{currentVersion:string, targetInfo:object, cliVersion?:string, force?:boolean}} args
 */
export function checkCompat({ currentVersion, targetInfo, cliVersion, force = false }) {
  const errors = [];
  const warnings = [];
  const targetVersion = targetInfo?.version;

  if (!targetVersion) {
    errors.push('升级源缺少 version,拒绝升级');
  } else {
    const cmp = compareVersion(targetVersion, currentVersion);
    if (cmp === null) {
      warnings.push(`无法比较版本 ${currentVersion} → ${targetVersion},已跳过版本顺序校验`);
    } else if (cmp < 0) {
      errors.push(`目标 v${targetVersion} 低于当前 v${currentVersion},拒绝降级(确需回退请用 kernel backups)`);
    }
  }

  const minCli = targetInfo?.minCliVersion;
  if (minCli && cliVersion) {
    const c = compareVersion(cliVersion, minCli);
    if (c === null) warnings.push(`无法比较 CLI 版本 ${cliVersion} 与要求 ${minCli}`);
    else if (c < 0) errors.push(`CLI v${cliVersion} 过低:内核 v${targetVersion} 要求 >= v${minCli},请升级内核(CLI 随 .kernel/ 一并更新)`);
  }

  const minKernel = targetInfo?.minKernelVersion;
  if (minKernel) {
    const c = compareVersion(currentVersion, minKernel);
    if (c === null) warnings.push(`无法比较当前内核 ${currentVersion} 与升级下限 ${minKernel}`);
    else if (c < 0) errors.push(`当前内核 v${currentVersion} 过低:v${targetVersion} 要求从 >= v${minKernel} 升级,请逐级升级`);
  }

  const migrations = migrationsBetween(targetInfo?.migrations, currentVersion, targetVersion);
  const breaking = migrations.filter((m) => m.breaking);
  if (breaking.length) warnings.push(`${breaking.length} 项破坏性变更需要人工确认`);

  if (force) {
    return {
      ok: true,
      forced: errors.length > 0 || breaking.length > 0,
      errors: [],
      warnings: [...warnings, '已通过 --force 跳过兼容拦截,请自行确认后果'],
      migrations,
      breaking,
    };
  }
  if (errors.length || breaking.length) {
    return { ok: false, forced: false, errors, warnings, migrations, breaking };
  }
  return { ok: true, forced: false, errors: [], warnings, migrations, breaking };
}

/** 把兼容判定结果格式化为终端输出(含人工步骤)。 */
export function formatCompat(result) {
  const lines = [];
  for (const e of result.errors ?? []) lines.push(`  ✗ ${e}`);
  for (const w of result.warnings ?? []) lines.push(`  ! ${w}`);
  if (result.breaking?.length) {
    lines.push('  破坏性变更(需确认后再升级,--force 可跳过):');
    for (const m of result.breaking) {
      lines.push(`    - ${m.from ?? '*'} → ${m.to ?? '*'}: ${m.summary ?? '(无说明)'}`);
      for (const step of m.manual ?? []) lines.push(`        ${step}`);
    }
  } else if (result.migrations?.length) {
    lines.push('  本次升级将执行的迁移说明:');
    for (const m of result.migrations) {
      lines.push(`    - ${m.from ?? '*'} → ${m.to ?? '*'}: ${m.summary ?? '(无说明)'}`);
      for (const step of m.manual ?? []) lines.push(`        ${step}`);
    }
  }
  return lines.join('\n');
}

/** 追加一条升级记录到项目根 .venus/upgrade-log.json(不进门禁、不进业务指纹)。 */
export function appendUpgradeLog(root, entry) {
  const file = path.join(root, LOG_PATH);
  fs.mkdirSync(path.dirname(file), { recursive: true });
  let log = [];
  try {
    const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
    if (Array.isArray(parsed)) log = parsed;
  } catch { /* 首次升级或文件损坏,重建 */ }
  log.push({
    at: new Date().toISOString(),
    from: entry.from,
    to: entry.to,
    source: entry.source ?? '(未记录)',
    backup: entry.backup ?? null,
    forced: Boolean(entry.forced),
    migrations: (entry.migrations ?? []).map((m) => m.summary ?? `${m.from} → ${m.to}`),
  });
  if (log.length > LOG_LIMIT) log = log.slice(-LOG_LIMIT);
  fs.writeFileSync(file, JSON.stringify(log, null, 2) + '\n');
  return file;
}

/** 读取升级历史;不存在返回空数组。 */
export function readUpgradeLog(root) {
  try {
    const parsed = JSON.parse(fs.readFileSync(path.join(root, LOG_PATH), 'utf8'));
    return Array.isArray(parsed) ? parsed : [];
  } catch {
    return [];
  }
}