seed-builtin.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import {
  2. existsSync,
  3. mkdirSync,
  4. readdirSync,
  5. readFileSync,
  6. rmSync,
  7. statSync,
  8. writeFileSync,
  9. type Dirent,
  10. type RmOptions,
  11. } from 'node:fs';
  12. import { join } from 'node:path';
  13. import yaml from 'js-yaml';
  14. import { logger } from '../common/logger.js';
  15. import { combinedSeedFingerprint, fingerprintSkillDir } from './seed-fingerprint.js';
  16. const SKILL_FILE = 'SKILL.md';
  17. /** Runtime marker: the combined fingerprint of the last fully successful seed. */
  18. const SEED_MARKER_FILE = '.seed-fingerprint';
  19. /** Build-time per-skill aggregates emitted by scripts/lib/seed-fingerprints.mjs. */
  20. const SEED_FINGERPRINTS_FILE = '.seed-fingerprints.json';
  21. /** Per-file manifest of the superseded incremental-sync design. */
  22. const LEGACY_MANIFEST_FILE = '.seed-manifest.json';
  23. /** Sibling backup dir of the retired pre-manifest backup/staging mechanism. */
  24. const LEGACY_BACKUP_DIR_SUFFIX = '.seed-backups';
  25. /** Temp-name marker used by both superseded seeding mechanisms. */
  26. const LEGACY_TMP_MARKER = '.tmp-seed';
  27. const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---/;
  28. const REMOVE_OPTIONS: RmOptions = {
  29. recursive: true,
  30. force: true,
  31. maxRetries: 3,
  32. retryDelay: 50,
  33. };
  34. export interface SeedBuiltinSkillsDeps {
  35. builtinSkillsDir: string;
  36. sourceDirs: string[];
  37. /** Return false to treat a source skill as absent (excluded from seeding). */
  38. isSkillEnabled?: (skillName: string) => boolean;
  39. }
  40. /**
  41. * Seed bundled builtin skills into `builtinSkillsDir` at startup.
  42. *
  43. * Marker-driven full reseed: `<builtinSkillsDir>/.seed-fingerprint` holds the
  44. * combined fingerprint (over the per-skill aggregates of every enabled
  45. * skill) of the last fully successful seed. When the marker matches the
  46. * current combined value and every enabled skill dir exists, the whole seed
  47. * is skipped without a single write. On any mismatch the dest dir is wiped
  48. * and every enabled skill copied fresh; the marker is written last, only
  49. * after every skill copied, so a crash or partial failure replays the whole
  50. * seed on the next startup (self-healing). User files placed inside
  51. * `builtinSkillsDir` are cleared on every rewrite — an accepted rev3
  52. * trade-off for mechanism simplicity.
  53. *
  54. * Must not import registry code. Fail-open everywhere: a broken skill or an
  55. * unreadable source never throws out of this function.
  56. *
  57. * Only asar-compatible fs APIs are used (readdirSync/readFileSync/
  58. * writeFileSync/mkdirSync/rmSync/statSync/existsSync).
  59. * `cpSync` is NOT patched by Electron for asar transparency, so copying from
  60. * an asar-packed source (e.g. `app.asar/node_modules/.../assets/skills/foo`)
  61. * would throw `ENOTDIR`. Works on macOS, Windows, and Linux.
  62. */
  63. export function seedBuiltinSkills(deps: SeedBuiltinSkillsDeps): void {
  64. const { builtinSkillsDir, sourceDirs, isSkillEnabled } = deps;
  65. cleanupLegacySeedArtifacts(builtinSkillsDir);
  66. // Union the skill sets of every readable source dir; candidate order is
  67. // priority order (e.g. the MAVIS_BUILTIN_SKILLS_DIR override is listed
  68. // first), so for a name present in several dirs the earliest readable
  69. // candidate wins. A candidate path may exist but not be a readable
  70. // directory (points at a file, EACCES, or a broken symlink). readdirSync
  71. // would throw and — because the host constructor calls this on the
  72. // unconditional startup path — take down local-runtime startup. Treat an
  73. // unreadable candidate as "absent": log and move on instead of throwing.
  74. let sawSourceDir = false;
  75. const sourceSkills = new Map<string, { src: string; buildAggregate: string | undefined }>();
  76. for (const candidate of sourceDirs) {
  77. if (!existsSync(candidate)) continue;
  78. let entries: Dirent[];
  79. try {
  80. entries = readdirSync(candidate, { withFileTypes: true });
  81. } catch (err) {
  82. logger.error(
  83. { sourceDir: candidate, err: errorMessage(err) },
  84. 'Failed to enumerate built-in skills source dir (skipping candidate, local-runtime will continue)',
  85. );
  86. continue;
  87. }
  88. sawSourceDir = true;
  89. const buildAggregates = loadSeedFingerprintsFile(candidate);
  90. for (const entry of entries) {
  91. if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
  92. if (sourceSkills.has(entry.name)) continue; // earlier candidate wins
  93. sourceSkills.set(entry.name, {
  94. src: join(candidate, entry.name),
  95. buildAggregate: buildAggregates?.get(entry.name),
  96. });
  97. }
  98. }
  99. // Fail-open no-op when no bundled source dir resolved (packaging glitch or a
  100. // transient MAVIS_BUILTIN_SKILLS_DIR outage): leave dest and marker
  101. // untouched so we never wipe already-seeded builtin skills that a prior
  102. // successful run installed.
  103. if (!sawSourceDir) {
  104. logger.warn(
  105. { builtinSkillsDir, sourceDirs },
  106. 'No bundled builtin skills source dir found; skipping seed to preserve existing .builtin-skills',
  107. );
  108. return;
  109. }
  110. // Resolve the enabled set and each skill's aggregate. A skill whose
  111. // aggregate cannot be computed is skipped this boot and withholds the
  112. // marker so the next startup retries the whole seed.
  113. const enabledSkills = new Map<string, { src: string; aggregate: string }>();
  114. let allOk = true;
  115. for (const [skillName, { src, buildAggregate }] of sourceSkills) {
  116. if (isSkillEnabled && !isSkillEnabled(skillName)) continue;
  117. if (buildAggregate !== undefined) {
  118. // Build-time entries are pre-vetted: generateSeedFingerprints omits
  119. // retired skills, so a listed entry needs no SKILL.md read here and the
  120. // fast path stays free of per-skill content reads.
  121. enabledSkills.set(skillName, { src, aggregate: buildAggregate });
  122. continue;
  123. }
  124. if (isSkillRuntimeRetiredFile(join(src, SKILL_FILE))) {
  125. logger.info({ skillName }, 'Skipped retired built-in skill');
  126. continue;
  127. }
  128. try {
  129. enabledSkills.set(skillName, { src, aggregate: fingerprintSkillDir(src).aggregate });
  130. } catch (err) {
  131. // Strict source walk: an unreadable entry fails the whole skill instead
  132. // of seeding a partial copy.
  133. allOk = false;
  134. logger.error(
  135. { skillName, err: errorMessage(err) },
  136. 'Failed to fingerprint built-in skill source (skipped this boot, local-runtime will continue)',
  137. );
  138. }
  139. }
  140. const aggregates = new Map<string, string>();
  141. for (const [skillName, { aggregate }] of enabledSkills) aggregates.set(skillName, aggregate);
  142. const combined = combinedSeedFingerprint(aggregates);
  143. // Fast path: marker matches and every enabled skill dir survives — the
  144. // whole seed is a no-op with zero writes.
  145. if (readSeedMarker(builtinSkillsDir) === combined) {
  146. let allPresent = true;
  147. for (const skillName of enabledSkills.keys()) {
  148. if (!existsSync(join(builtinSkillsDir, skillName))) {
  149. allPresent = false;
  150. break;
  151. }
  152. }
  153. if (allPresent) return;
  154. }
  155. // Wipe + full reseed. rmSync never follows symlinks, so a user-planted link
  156. // inside the dest tree is removed as a link and its target stays intact.
  157. try {
  158. rmSync(builtinSkillsDir, REMOVE_OPTIONS);
  159. mkdirSync(builtinSkillsDir, { recursive: true });
  160. } catch (err) {
  161. logger.error(
  162. { builtinSkillsDir, err: errorMessage(err) },
  163. 'Failed to reset built-in skills dir for seeding (kept existing content, local-runtime will continue)',
  164. );
  165. return;
  166. }
  167. for (const [skillName, { src }] of enabledSkills) {
  168. const dest = join(builtinSkillsDir, skillName);
  169. try {
  170. copySkillDir(src, dest, true);
  171. } catch (err) {
  172. allOk = false;
  173. try {
  174. rmSync(dest, REMOVE_OPTIONS);
  175. } catch {
  176. // A stuck partial copy is cleared by the replay on the next startup.
  177. }
  178. logger.error(
  179. { skillName, err: errorMessage(err) },
  180. 'Failed to seed built-in skill (skipped this boot, local-runtime will continue)',
  181. );
  182. }
  183. }
  184. // The marker is the commit point: written only after every enabled skill
  185. // seeded. Withholding it (or crashing before this line) makes the next
  186. // startup replay the whole seed.
  187. if (!allOk) return;
  188. try {
  189. writeFileSync(join(builtinSkillsDir, SEED_MARKER_FILE), combined);
  190. } catch (err) {
  191. logger.error(
  192. { builtinSkillsDir, err: errorMessage(err) },
  193. 'Failed to write built-in skill seed marker (seed replays next startup, local-runtime will continue)',
  194. );
  195. }
  196. }
  197. /**
  198. * Remove leftovers of the superseded seeding mechanisms: the per-file
  199. * `.seed-manifest.json`, the sibling `<builtinSkillsDir>.seed-backups` dir,
  200. * and `.tmp-seed` staging residue at the dest top level. No restoration —
  201. * the marker mechanism replays the whole seed anyway.
  202. */
  203. function cleanupLegacySeedArtifacts(builtinSkillsDir: string): void {
  204. const legacyPaths: string[] = [];
  205. const manifestFile = join(builtinSkillsDir, LEGACY_MANIFEST_FILE);
  206. if (existsSync(manifestFile)) legacyPaths.push(manifestFile);
  207. const backupDir = `${builtinSkillsDir}${LEGACY_BACKUP_DIR_SUFFIX}`;
  208. if (existsSync(backupDir)) legacyPaths.push(backupDir);
  209. if (existsSync(builtinSkillsDir)) {
  210. try {
  211. for (const name of readdirSync(builtinSkillsDir)) {
  212. if (name.includes(LEGACY_TMP_MARKER)) legacyPaths.push(join(builtinSkillsDir, name));
  213. }
  214. } catch {
  215. // An unreadable dest dir surfaces via the seeding pass itself.
  216. }
  217. }
  218. for (const path of legacyPaths) {
  219. try {
  220. rmSync(path, REMOVE_OPTIONS);
  221. } catch (err) {
  222. logger.warn(
  223. { path, err: errorMessage(err) },
  224. 'Failed to remove legacy built-in skill seeding artifact (local-runtime will continue)',
  225. );
  226. }
  227. }
  228. }
  229. /**
  230. * Load the build-time `<sourceDir>/.seed-fingerprints.json` as a
  231. * name → aggregate map. Returns undefined (never throws) when the file is
  232. * missing, unreadable, invalid JSON, or has an unexpected shape — callers
  233. * fall back to runtime fingerprinting. Entries are only ever used as
  234. * aggregate lookups keyed by real dir entry names, never as paths.
  235. */
  236. function loadSeedFingerprintsFile(sourceDir: string): Map<string, string> | undefined {
  237. try {
  238. const parsed: unknown = JSON.parse(
  239. readFileSync(join(sourceDir, SEED_FINGERPRINTS_FILE), 'utf8'),
  240. );
  241. if (!isRecord(parsed) || parsed.schemaVersion !== 1 || !isRecord(parsed.skills)) {
  242. return undefined;
  243. }
  244. const aggregates = new Map<string, string>();
  245. for (const [skillName, entry] of Object.entries(parsed.skills)) {
  246. if (!isRecord(entry) || typeof entry.aggregate !== 'string') return undefined;
  247. aggregates.set(skillName, entry.aggregate);
  248. }
  249. return aggregates;
  250. } catch {
  251. return undefined;
  252. }
  253. }
  254. /** Read the seed marker; undefined when missing or unreadable (→ full seed). */
  255. function readSeedMarker(builtinSkillsDir: string): string | undefined {
  256. try {
  257. return readFileSync(join(builtinSkillsDir, SEED_MARKER_FILE), 'utf8').trim();
  258. } catch {
  259. return undefined;
  260. }
  261. }
  262. /**
  263. * asar-safe recursive copy of one skill dir (see the seedBuiltinSkills doc
  264. * for why cpSync is off-limits). Reads the source listing before creating
  265. * the dest, so a broken source (dangling symlink root) fails without leaving
  266. * a partial dest. Empty non-root directories are skipped — the fingerprint
  267. * ignores them, so copying them would desync dest from the aggregate for no
  268. * benefit. Symlink entries are read through as files; a link to a directory
  269. * fails the read (EISDIR) and thereby the whole skill — the copy never
  270. * traverses links.
  271. */
  272. function copySkillDir(src: string, dest: string, isRoot: boolean): void {
  273. const entries = readdirSync(src, { withFileTypes: true });
  274. if (!isRoot && entries.length === 0) return;
  275. mkdirSync(dest, { recursive: true });
  276. for (const entry of entries) {
  277. const srcPath = join(src, entry.name);
  278. const destPath = join(dest, entry.name);
  279. if (entry.isDirectory()) {
  280. copySkillDir(srcPath, destPath, false);
  281. } else if (entry.isFile() || entry.isSymbolicLink()) {
  282. const content = readFileSync(srcPath);
  283. if (process.platform === 'win32') {
  284. writeFileSync(destPath, content);
  285. } else {
  286. // writeFileSync applies `mode` on creation, restoring the POSIX
  287. // execute bit without chmodSync (dest was just wiped, so files are
  288. // always freshly created here).
  289. const executable = (statSync(srcPath).mode & 0o111) !== 0;
  290. writeFileSync(destPath, content, { mode: executable ? 0o755 : 0o644 });
  291. }
  292. }
  293. // Skip other entry types (sockets, block devices, etc.)
  294. }
  295. }
  296. function errorMessage(err: unknown): string {
  297. return err instanceof Error ? err.message : String(err);
  298. }
  299. function isRecord(value: unknown): value is Record<string, unknown> {
  300. return typeof value === 'object' && value !== null && !Array.isArray(value);
  301. }
  302. function isSkillRuntimeRetiredFile(skillFilePath: string): boolean {
  303. try {
  304. const content = readFileSync(skillFilePath, 'utf8');
  305. const match = FRONTMATTER_RE.exec(content);
  306. if (!match?.[1]) return false;
  307. const data = yaml.load(match[1]);
  308. if (!data || typeof data !== 'object' || Array.isArray(data)) return false;
  309. return (data as Record<string, unknown>).retired === true;
  310. } catch {
  311. return false;
  312. }
  313. }