@mindbricks/genesis-set 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/LICENSE +202 -0
  3. package/README.md +147 -2
  4. package/bin/genesis-set.mjs +153 -0
  5. package/corpus/README.md +25 -0
  6. package/corpus/genesis/compile-results.md +246 -0
  7. package/corpus/genesis/compiler-api.md +265 -0
  8. package/corpus/genesis/custom-code.md +519 -0
  9. package/corpus/genesis/deploy.md +190 -0
  10. package/corpus/genesis/pitfalls.md +231 -0
  11. package/corpus/genesis/procedures/README.md +17 -0
  12. package/corpus/genesis/procedures/agent-hub-blueprint.md +13 -0
  13. package/corpus/genesis/procedures/auth-blueprint.md +14 -0
  14. package/corpus/genesis/procedures/bff-blueprint.md +16 -0
  15. package/corpus/genesis/procedures/blueprint-authoring.md +16 -0
  16. package/corpus/genesis/procedures/howto-mail-to-tasks.md +26 -0
  17. package/corpus/genesis/procedures/howto-payment-flow.md +112 -0
  18. package/corpus/genesis/procedures/howto-subscription.md +33 -0
  19. package/corpus/genesis/procedures/notifications-blueprint.md +13 -0
  20. package/corpus/genesis/procedures/patterns-catalog.md +12 -0
  21. package/corpus/genesis/procedures/project-lifecycle.md +27 -0
  22. package/corpus/genesis/run-locally.md +310 -0
  23. package/corpus/genesis/testing.md +532 -0
  24. package/lib/config-cli.mjs +179 -0
  25. package/lib/install.mjs +639 -0
  26. package/lib/mcp-config.mjs +220 -0
  27. package/lib/semver.mjs +94 -0
  28. package/mcp/blueprint.mjs +64 -0
  29. package/mcp/client.mjs +141 -0
  30. package/mcp/config.mjs +166 -0
  31. package/mcp/key-page-html.mjs +275 -0
  32. package/mcp/key-page.mjs +217 -0
  33. package/mcp/key-store.mjs +204 -0
  34. package/mcp/key-tools.mjs +225 -0
  35. package/mcp/server.mjs +164 -0
  36. package/mcp/tools.mjs +270 -0
  37. package/package.json +43 -4
  38. package/skills/genesis-compiler-api/SKILL.md +56 -0
  39. package/skills/genesis-deploy/SKILL.md +36 -0
  40. package/skills/genesis-generated-code/SKILL.md +48 -0
  41. package/skills/genesis-run-and-test/SKILL.md +43 -0
@@ -0,0 +1,639 @@
1
+ // install / update / uninstall / doctor for the genesis-set package.
2
+ //
3
+ // genesis-set sits on mind-set (the OpenAPPL layer): it adds the Genesis
4
+ // compiler skills and never copies or replaces a mind-set skill. Layout:
5
+ // <data>/<version>/ the genesis-set corpus of that version
6
+ // <data>/current link to the corpus the skills point at
7
+ // <data>/installed.json the manifest: every path install wrote
8
+ // <claude>/skills/genesis-* Claude Code skills (<claude> = ~/.claude)
9
+ // <agents>/skills/genesis-* Codex skills (<agents> = ~/.agents)
10
+ // <data>/mcp/ the genesis-set MCP server (the genesis_* tools),
11
+ // registered with each agent at user scope
12
+ // (~/.claude.json, ~/.codex/config.toml); see mcp-config.mjs
13
+ // <data>/config.json the Genesis API key and API base, when the user
14
+ // stores them with `genesis-set config` (never a project file)
15
+ // <data> is ~/.genesis-set unless GENESIS_SET_HOME names another folder.
16
+ // mind-set keeps its own data folder (~/.mind-set, or MIND_SET_HOME) and is
17
+ // installed by its own CLI: when it is missing, or older than the range in
18
+ // package.json `dependencies["@mindbricks/mind-set"]`, install runs the mind-set package
19
+ // that came with genesis-set. Nothing is written into a project folder.
20
+
21
+ import { spawnSync } from 'node:child_process';
22
+ import fs from 'node:fs';
23
+ import { createRequire } from 'node:module';
24
+ import os from 'node:os';
25
+ import path from 'node:path';
26
+ import { REGISTER, REGISTRATION, UNREGISTER, copyServer, mcpServerDir, mcpServerFile } from './mcp-config.mjs';
27
+ import { compareVersions, satisfies } from './semver.mjs';
28
+ import { portalKeysUrl, resolveSettings } from '../mcp/config.mjs';
29
+
30
+ export const PACKAGE_NAME = 'genesis-set';
31
+ export const MARKER = '.genesis-set.json';
32
+ export const MIND_SET_MARKER = '.mind-set.json';
33
+ export const MANIFEST = 'installed.json';
34
+ export const CORPUS_PLACEHOLDER = '{{CORPUS}}';
35
+ export const MIND_SET_PLACEHOLDER = '{{MIND_SET}}';
36
+ export const SKILL_PREFIX = 'genesis-';
37
+ /** The npm name of mind-set (the command and the installed manifest say `mind-set`). */
38
+ export const MIND_SET_NPM = '@mindbricks/mind-set';
39
+ /** The environment variable that holds the Genesis Compiler API key (never a file in the project). */
40
+ export const API_KEY_ENV = 'GENESIS_API_KEY';
41
+ const VERSION_DIR = /^\d+\.\d+\.\d+([-+][0-9A-Za-z.-]+)?$/;
42
+
43
+ /** Resolves every location from the environment (HOME, GENESIS_SET_HOME, MIND_SET_HOME, PATH). */
44
+ export function resolveContext({ env = process.env, pkgRoot, pkg, out, dryRun = false }) {
45
+ const home = env.HOME || env.USERPROFILE || os.homedir();
46
+ const dataDir = env.GENESIS_SET_HOME ? path.resolve(env.GENESIS_SET_HOME) : path.join(home, '.genesis-set');
47
+ const mindSetDir = env.MIND_SET_HOME ? path.resolve(env.MIND_SET_HOME) : path.join(home, '.mind-set');
48
+ return {
49
+ env,
50
+ home,
51
+ dataDir,
52
+ mindSetDir,
53
+ pathEnv: env.PATH || env.Path || '',
54
+ pkgRoot,
55
+ nodePath: env.GENESIS_SET_NODE ? path.resolve(env.GENESIS_SET_NODE) : process.execPath,
56
+ version: pkg.version,
57
+ mindSetRange: pkg.dependencies?.[MIND_SET_NPM] ?? null,
58
+ dryRun,
59
+ out,
60
+ agents: {
61
+ claude: {
62
+ name: 'claude',
63
+ label: 'Claude Code',
64
+ configDir: path.join(home, '.claude'),
65
+ skillsDir: path.join(home, '.claude', 'skills'),
66
+ flag: '--claude',
67
+ },
68
+ codex: {
69
+ name: 'codex',
70
+ label: 'Codex',
71
+ configDir: path.join(home, '.codex'),
72
+ skillsDir: path.join(home, '.agents', 'skills'),
73
+ flag: '--codex',
74
+ },
75
+ },
76
+ };
77
+ }
78
+
79
+ function exists(p) {
80
+ try {
81
+ fs.lstatSync(p);
82
+ return true;
83
+ } catch {
84
+ return false;
85
+ }
86
+ }
87
+
88
+ function readJson(p) {
89
+ try {
90
+ return JSON.parse(fs.readFileSync(p, 'utf8'));
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
96
+ function remove(p) {
97
+ fs.rmSync(p, { recursive: true, force: true });
98
+ }
99
+
100
+ function plural(n, word) {
101
+ return `${n} ${word}${n === 1 ? '' : 's'}`;
102
+ }
103
+
104
+ function onPath(ctx, binary) {
105
+ const exts = process.platform === 'win32' ? ['', '.exe', '.cmd', '.bat'] : [''];
106
+ for (const dir of ctx.pathEnv.split(path.delimiter)) {
107
+ if (!dir) continue;
108
+ for (const ext of exts) {
109
+ try {
110
+ if (fs.statSync(path.join(dir, binary + ext)).isFile()) return true;
111
+ } catch {
112
+ // not in this PATH entry
113
+ }
114
+ }
115
+ }
116
+ return false;
117
+ }
118
+
119
+ /** Which agents are on this machine, and why we think so. */
120
+ export function detectAgents(ctx) {
121
+ const found = {};
122
+ found.claude = exists(ctx.agents.claude.configDir) ? `found ${ctx.agents.claude.configDir}` : null;
123
+ if (exists(ctx.agents.codex.configDir)) found.codex = `found ${ctx.agents.codex.configDir}`;
124
+ else if (onPath(ctx, 'codex')) found.codex = 'found codex on PATH';
125
+ else found.codex = null;
126
+ return found;
127
+ }
128
+
129
+ /**
130
+ * Which agents a command writes to. Explicit flags win (and force an agent
131
+ * that is not detected); with no flag, every detected agent; for `update`,
132
+ * also every agent the previous install wrote to.
133
+ */
134
+ export function chooseAgents(ctx, flags, { includeManifest = false } = {}) {
135
+ const chosen = [];
136
+ if (flags.claude) chosen.push('claude');
137
+ if (flags.codex) chosen.push('codex');
138
+ if (chosen.length) return chosen;
139
+ const detected = detectAgents(ctx);
140
+ const set = new Set(Object.keys(detected).filter((a) => detected[a]));
141
+ if (includeManifest) {
142
+ for (const a of Object.keys(readManifest(ctx)?.agents ?? {})) if (ctx.agents[a]) set.add(a);
143
+ }
144
+ return ['claude', 'codex'].filter((a) => set.has(a));
145
+ }
146
+
147
+ export function readManifest(ctx) {
148
+ return readJson(path.join(ctx.dataDir, MANIFEST));
149
+ }
150
+
151
+ function readMarker(dir, marker = MARKER, pkg = PACKAGE_NAME) {
152
+ const m = readJson(path.join(dir, marker));
153
+ return m && m.package === pkg ? m : null;
154
+ }
155
+
156
+ function packageSkills(ctx) {
157
+ const dir = path.join(ctx.pkgRoot, 'skills');
158
+ let names = [];
159
+ try {
160
+ names = fs
161
+ .readdirSync(dir, { withFileTypes: true })
162
+ .filter((d) => d.isDirectory() && exists(path.join(dir, d.name, 'SKILL.md')))
163
+ .map((d) => d.name)
164
+ .sort();
165
+ } catch {
166
+ // no skills folder
167
+ }
168
+ return { dir, names };
169
+ }
170
+
171
+ function copyDir(src, dest, transform) {
172
+ fs.mkdirSync(dest, { recursive: true });
173
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
174
+ const s = path.join(src, entry.name);
175
+ const d = path.join(dest, entry.name);
176
+ if (entry.isDirectory()) copyDir(s, d, transform);
177
+ else if (entry.isFile()) {
178
+ if (transform && entry.name.endsWith('.md')) fs.writeFileSync(d, transform(fs.readFileSync(s, 'utf8')));
179
+ else fs.copyFileSync(s, d);
180
+ }
181
+ }
182
+ }
183
+
184
+ /** Points `<data>/current` at the corpus: a symlink (a junction on Windows), else a copy. */
185
+ function linkCurrent(ctx, corpusDir) {
186
+ const current = path.join(ctx.dataDir, 'current');
187
+ remove(current);
188
+ try {
189
+ fs.symlinkSync(corpusDir, current, process.platform === 'win32' ? 'junction' : 'dir');
190
+ } catch {
191
+ copyDir(corpusDir, current);
192
+ }
193
+ return current;
194
+ }
195
+
196
+ // ── mind-set ────────────────────────────────────────────────────────
197
+
198
+ /** The installed mind-set: its manifest, or null when it is not installed. */
199
+ export function installedMindSet(ctx) {
200
+ const m = readJson(path.join(ctx.mindSetDir, MANIFEST));
201
+ return m && m.package === 'mind-set' ? m : null;
202
+ }
203
+
204
+ /** The mind-set corpus the genesis-set skills point at (stable across mind-set updates). */
205
+ export function mindSetCorpus(ctx) {
206
+ return path.join(ctx.mindSetDir, 'current');
207
+ }
208
+
209
+ /**
210
+ * The mind-set package that came with genesis-set (its npm dependency), or the
211
+ * folder GENESIS_SET_MIND_SET_PACKAGE names. Null when neither is there.
212
+ */
213
+ export function bundledMindSet(ctx) {
214
+ const candidates = [];
215
+ if (ctx.env.GENESIS_SET_MIND_SET_PACKAGE) candidates.push(path.resolve(ctx.env.GENESIS_SET_MIND_SET_PACKAGE));
216
+ try {
217
+ const req = createRequire(path.join(ctx.pkgRoot, 'package.json'));
218
+ candidates.push(path.dirname(req.resolve(`${MIND_SET_NPM}/package.json`)));
219
+ } catch {
220
+ // not resolvable from this package
221
+ }
222
+ for (const dir of candidates) {
223
+ const pkg = readJson(path.join(dir, 'package.json'));
224
+ const bin = path.join(dir, 'bin', 'mind-set.mjs');
225
+ if ((pkg?.name === MIND_SET_NPM || pkg?.name === 'mind-set') && exists(bin)) return { dir, version: String(pkg.version), bin };
226
+ }
227
+ return null;
228
+ }
229
+
230
+ /** Where mind-set stands against the range: ok, missing, old (an update fixes it) or incompatible. */
231
+ export function mindSetState(ctx) {
232
+ const installed = installedMindSet(ctx);
233
+ const version = installed?.version ?? null;
234
+ if (!version) return { state: 'missing', version: null };
235
+ const ok = ctx.mindSetRange ? satisfies(version, ctx.mindSetRange) : true;
236
+ if (ok) return { state: 'ok', version };
237
+ const bundled = bundledMindSet(ctx);
238
+ if (bundled && satisfies(bundled.version, ctx.mindSetRange) && compareVersions(version, bundled.version) < 0) {
239
+ return { state: 'old', version };
240
+ }
241
+ return { state: 'incompatible', version };
242
+ }
243
+
244
+ function runMindSet(ctx, bundled, command, agentNames) {
245
+ const args = [bundled.bin, command, ...agentNames.map((a) => ctx.agents[a].flag)];
246
+ if (ctx.dryRun) args.push('--dry-run');
247
+ const res = spawnSync(process.execPath, args, { env: ctx.env, encoding: 'utf8' });
248
+ for (const line of `${res.stdout ?? ''}${res.stderr ?? ''}`.split('\n')) if (line) ctx.out(` mind-set: ${line}`);
249
+ return res.status ?? 1;
250
+ }
251
+
252
+ /**
253
+ * Makes sure a compatible mind-set is installed for `agentNames`: installs the
254
+ * bundled mind-set when none is installed, updates an older one, and leaves a
255
+ * compatible one alone. Returns 0, or 1 when mind-set cannot be made compatible.
256
+ */
257
+ export function ensureMindSet(ctx, agentNames) {
258
+ const st = mindSetState(ctx);
259
+ const range = ctx.mindSetRange ?? 'any';
260
+ if (st.state === 'ok') {
261
+ // A compatible mind-set; make sure every chosen agent has its skills.
262
+ const have = installedMindSet(ctx)?.agents ?? {};
263
+ const missing = agentNames.filter((a) => !have[a]);
264
+ if (!missing.length) {
265
+ ctx.out(`mind-set ${st.version} is installed (genesis-set needs ${range})`);
266
+ return 0;
267
+ }
268
+ const bundled = bundledMindSet(ctx);
269
+ if (!bundled) {
270
+ ctx.out(`mind-set ${st.version} has no skills for ${missing.map((a) => ctx.agents[a].label).join(', ')}; run "mind-set install"`);
271
+ return 1;
272
+ }
273
+ ctx.out(`mind-set ${st.version}: adding its skills for ${missing.map((a) => ctx.agents[a].label).join(', ')}`);
274
+ return runMindSet(ctx, bundled, 'install', missing);
275
+ }
276
+ if (st.state === 'incompatible') {
277
+ ctx.out(
278
+ `error: mind-set ${st.version} is installed but genesis-set ${ctx.version} needs ${range}; ` +
279
+ `install a genesis-set release made for it, or a mind-set in that range ("npm install -g ${MIND_SET_NPM}@<version>", then "mind-set install")`,
280
+ );
281
+ return 1;
282
+ }
283
+ const bundled = bundledMindSet(ctx);
284
+ if (!bundled) {
285
+ ctx.out(
286
+ `error: mind-set is ${st.state === 'missing' ? 'not installed' : `${st.version}, older than ${range}`} ` +
287
+ `and the mind-set package that comes with genesis-set was not found; run "npm install -g ${MIND_SET_NPM}" and "mind-set install" first`,
288
+ );
289
+ return 1;
290
+ }
291
+ if (!satisfies(bundled.version, ctx.mindSetRange ?? '*')) {
292
+ ctx.out(`error: the bundled mind-set ${bundled.version} is outside ${range}; reinstall genesis-set`);
293
+ return 1;
294
+ }
295
+ ctx.out(
296
+ st.state === 'missing'
297
+ ? `mind-set is not installed: installing mind-set ${bundled.version} (genesis-set needs ${range})`
298
+ : `mind-set ${st.version} is older than ${range}: updating to ${bundled.version}`,
299
+ );
300
+ return runMindSet(ctx, bundled, st.state === 'missing' ? 'install' : 'update', agentNames);
301
+ }
302
+
303
+ // ── install / update / uninstall / doctor ────────────────────────────
304
+
305
+ /**
306
+ * Makes mind-set compatible, copies the corpus and writes the genesis-set
307
+ * skills for `agentNames`. Exit code 0 when everything chosen was written, 1
308
+ * when mind-set could not be made compatible, a foreign or mind-set folder
309
+ * blocked a skill, or the package is incomplete.
310
+ */
311
+ export function install(ctx, agentNames, { force = false, skipMindSet = false, mcp = true } = {}) {
312
+ const say = ctx.out;
313
+ const act = (msg) => say(`${ctx.dryRun ? 'would ' : ''}${msg}`);
314
+ const srcCorpus = path.join(ctx.pkgRoot, 'corpus');
315
+ const skills = packageSkills(ctx);
316
+ if (!exists(srcCorpus)) {
317
+ say(`error: this package has no corpus/ folder (${srcCorpus})`);
318
+ return 1;
319
+ }
320
+ if (skills.names.length === 0) {
321
+ say(`error: this package has no skills under ${skills.dir}`);
322
+ return 1;
323
+ }
324
+ const unprefixed = skills.names.filter((s) => !s.startsWith(SKILL_PREFIX));
325
+ if (unprefixed.length) {
326
+ say(`error: skill names must start with "${SKILL_PREFIX}": ${unprefixed.join(', ')}`);
327
+ return 1;
328
+ }
329
+ if (agentNames.length === 0) {
330
+ say(
331
+ 'error: no supported agent found (looked for ~/.claude, ~/.codex and codex on PATH).\n' +
332
+ 'Re-run with --claude and/or --codex to install for an agent anyway.',
333
+ );
334
+ return 1;
335
+ }
336
+ if (!skipMindSet) {
337
+ const code = ensureMindSet(ctx, agentNames);
338
+ if (code !== 0) return code;
339
+ }
340
+
341
+ const previous = readManifest(ctx);
342
+ const corpusDir = path.join(ctx.dataDir, ctx.version);
343
+ act(`copy corpus ${srcCorpus} -> ${corpusDir}`);
344
+ if (!ctx.dryRun) {
345
+ remove(corpusDir);
346
+ copyDir(srcCorpus, corpusDir);
347
+ }
348
+ const current = path.join(ctx.dataDir, 'current');
349
+ act(`link ${current} -> ${corpusDir}`);
350
+ if (!ctx.dryRun) linkCurrent(ctx, corpusDir);
351
+
352
+ const mindSet = mindSetCorpus(ctx);
353
+ const fill = (text) => text.split(CORPUS_PLACEHOLDER).join(corpusDir).split(MIND_SET_PLACEHOLDER).join(mindSet);
354
+ const agents = { ...(previous?.agents ?? {}) };
355
+ let blocked = 0;
356
+ const stamp = new Date().toISOString();
357
+ for (const name of agentNames) {
358
+ const agent = ctx.agents[name];
359
+ const written = [];
360
+ for (const skill of skills.names) {
361
+ const dest = path.join(agent.skillsDir, skill);
362
+ if (readMarker(dest, MIND_SET_MARKER, 'mind-set')) {
363
+ // never, not even with --force: mind-set owns that folder
364
+ say(`skip ${agent.label} skill ${skill}: ${dest} belongs to mind-set and is never replaced by genesis-set`);
365
+ blocked++;
366
+ continue;
367
+ }
368
+ const ours = readMarker(dest);
369
+ if (exists(dest) && !ours) {
370
+ if (!force) {
371
+ say(
372
+ `skip ${agent.label} skill ${skill}: ${dest} exists and was not written by genesis-set ` +
373
+ '(use --force to replace it; the old folder is kept as a backup)',
374
+ );
375
+ blocked++;
376
+ continue;
377
+ }
378
+ const backup = path.join(ctx.dataDir, 'backup', `${name}-${skill}-${stamp.replace(/[:.]/g, '-')}`);
379
+ act(`back up foreign ${dest} -> ${backup}`);
380
+ if (!ctx.dryRun) {
381
+ fs.mkdirSync(path.dirname(backup), { recursive: true });
382
+ fs.cpSync(dest, backup, { recursive: true });
383
+ }
384
+ }
385
+ act(`write ${agent.label} skill ${skill} -> ${dest}`);
386
+ if (!ctx.dryRun) {
387
+ remove(dest);
388
+ copyDir(path.join(skills.dir, skill), dest, fill);
389
+ fs.writeFileSync(
390
+ path.join(dest, MARKER),
391
+ `${JSON.stringify({ package: PACKAGE_NAME, version: ctx.version, corpus: corpusDir, mindSet }, null, 2)}\n`,
392
+ );
393
+ }
394
+ written.push(skill);
395
+ }
396
+ for (const old of previous?.agents?.[name]?.skills ?? []) {
397
+ if (skills.names.includes(old)) continue;
398
+ const dest = path.join(agent.skillsDir, old);
399
+ if (!readMarker(dest)) continue;
400
+ act(`remove retired ${agent.label} skill ${old} (${dest})`);
401
+ if (!ctx.dryRun) remove(dest);
402
+ }
403
+ agents[name] = { skillsDir: agent.skillsDir, corpus: corpusDir, version: ctx.version, skills: written };
404
+ }
405
+
406
+ // The MCP server: one copy under <data>/mcp/, registered with each chosen agent.
407
+ const mcpAgents = { ...(previous?.mcp?.agents ?? {}) };
408
+ let mcpRegistered = 0;
409
+ if (mcp) {
410
+ if (!exists(path.join(ctx.pkgRoot, 'mcp', 'server.mjs'))) {
411
+ say(`error: this package has no mcp/server.mjs`);
412
+ return 1;
413
+ }
414
+ act(`copy MCP server ${path.join(ctx.pkgRoot, 'mcp')} -> ${mcpServerDir(ctx)}`);
415
+ if (!ctx.dryRun) copyServer(ctx);
416
+ for (const name of agentNames) {
417
+ const r = REGISTER[name](ctx, { force });
418
+ if (r.status === 'written') {
419
+ act(r.message);
420
+ mcpAgents[name] = { registered: true };
421
+ mcpRegistered++;
422
+ } else {
423
+ say(`skip ${ctx.agents[name].label} MCP server: ${r.message}`);
424
+ blocked++;
425
+ }
426
+ }
427
+ }
428
+
429
+ const manifest = {
430
+ package: PACKAGE_NAME,
431
+ version: ctx.version,
432
+ mindSetRange: ctx.mindSetRange,
433
+ installedAt: stamp,
434
+ dataDir: ctx.dataDir,
435
+ corpus: corpusDir,
436
+ current,
437
+ mindSetCorpus: mindSet,
438
+ corpora: [...new Set([...(previous?.corpora ?? []), corpusDir])],
439
+ agents,
440
+ mcp: mcp || previous?.mcp ? { server: mcpServerFile(ctx), agents: mcpAgents } : undefined,
441
+ };
442
+ manifest.paths = [
443
+ ...manifest.corpora,
444
+ current,
445
+ ...(manifest.mcp ? [mcpServerDir(ctx)] : []),
446
+ ...Object.values(agents).flatMap((a) => a.skills.map((s) => path.join(a.skillsDir, s))),
447
+ ];
448
+ act(`record ${manifest.paths.length} paths in ${path.join(ctx.dataDir, MANIFEST)}`);
449
+ if (!ctx.dryRun) {
450
+ fs.mkdirSync(ctx.dataDir, { recursive: true });
451
+ fs.writeFileSync(path.join(ctx.dataDir, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
452
+ }
453
+ const done = agentNames.map((a) => ctx.agents[a].label).join(', ');
454
+ say(
455
+ `${ctx.dryRun ? 'dry run: nothing written. ' : ''}genesis-set ${ctx.version}: ` +
456
+ `${plural(skills.names.length, 'skill')} for ${done}; corpus at ${corpusDir}` +
457
+ (mcp ? `; MCP server for ${plural(mcpRegistered, 'agent')}` : '') +
458
+ (blocked ? `; ${plural(blocked, 'skill')} skipped` : ''),
459
+ );
460
+ return blocked ? 1 : 0;
461
+ }
462
+
463
+ /** Install, then delete every corpus version no installed skill points at. */
464
+ export function update(ctx, agentNames, opts = {}) {
465
+ const code = install(ctx, agentNames, opts);
466
+ if (code !== 0 && !readManifest(ctx)) return code;
467
+ const manifest = readManifest(ctx);
468
+ const keep = new Set([path.join(ctx.dataDir, ctx.version)]);
469
+ for (const a of Object.values(manifest?.agents ?? {})) if (a.corpus) keep.add(a.corpus);
470
+ let entries = [];
471
+ try {
472
+ entries = fs.readdirSync(ctx.dataDir, { withFileTypes: true });
473
+ } catch {
474
+ // nothing installed yet (dry run)
475
+ }
476
+ const removed = [];
477
+ for (const e of entries) {
478
+ if (!e.isDirectory() || !VERSION_DIR.test(e.name)) continue;
479
+ const dir = path.join(ctx.dataDir, e.name);
480
+ if (keep.has(dir)) continue;
481
+ ctx.out(`${ctx.dryRun ? 'would ' : ''}remove old corpus ${dir}`);
482
+ if (!ctx.dryRun) remove(dir);
483
+ removed.push(dir);
484
+ }
485
+ if (manifest && removed.length && !ctx.dryRun) {
486
+ manifest.corpora = (manifest.corpora ?? []).filter((c) => !removed.includes(c));
487
+ manifest.paths = (manifest.paths ?? []).filter((p) => !removed.includes(p));
488
+ fs.writeFileSync(path.join(ctx.dataDir, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
489
+ }
490
+ return code;
491
+ }
492
+
493
+ /** Removes exactly what the manifest lists; mind-set is never touched. */
494
+ export function uninstall(ctx) {
495
+ const manifest = readManifest(ctx);
496
+ if (!manifest) {
497
+ ctx.out(`nothing to uninstall: no ${path.join(ctx.dataDir, MANIFEST)}`);
498
+ return 0;
499
+ }
500
+ const act = (msg) => ctx.out(`${ctx.dryRun ? 'would ' : ''}${msg}`);
501
+ for (const name of Object.keys(manifest.mcp?.agents ?? {})) {
502
+ if (!UNREGISTER[name]) continue;
503
+ const r = UNREGISTER[name](ctx);
504
+ if (r.status === 'removed') act(r.message);
505
+ else ctx.out(r.message);
506
+ }
507
+ const skillDirs = new Set(
508
+ Object.values(manifest.agents ?? {}).flatMap((a) => (a.skills ?? []).map((s) => path.join(a.skillsDir, s))),
509
+ );
510
+ const inData = (p) => {
511
+ const rel = path.relative(ctx.dataDir, p);
512
+ return rel && !rel.startsWith('..') && !path.isAbsolute(rel);
513
+ };
514
+ for (const p of manifest.paths ?? []) {
515
+ if (!exists(p)) continue;
516
+ if (skillDirs.has(p)) {
517
+ if (!readMarker(p)) {
518
+ ctx.out(`keep ${p}: it no longer carries the genesis-set marker`);
519
+ continue;
520
+ }
521
+ } else if (!inData(p)) {
522
+ ctx.out(`keep ${p}: outside ${ctx.dataDir} and not a genesis-set skill`);
523
+ continue;
524
+ }
525
+ act(`remove ${p}`);
526
+ if (!ctx.dryRun) remove(p);
527
+ }
528
+ act(`remove ${path.join(ctx.dataDir, MANIFEST)}`);
529
+ if (!ctx.dryRun) {
530
+ remove(path.join(ctx.dataDir, MANIFEST));
531
+ try {
532
+ const left = fs.readdirSync(ctx.dataDir);
533
+ if (left.length === 0) fs.rmdirSync(ctx.dataDir);
534
+ else ctx.out(`kept ${ctx.dataDir} (it still holds: ${left.join(', ')})`);
535
+ } catch {
536
+ // already gone
537
+ }
538
+ }
539
+ ctx.out(
540
+ `${ctx.dryRun ? 'dry run: nothing removed. ' : ''}genesis-set uninstalled; mind-set is left as it is ` +
541
+ '("mind-set uninstall" removes it)' +
542
+ (exists(path.join(ctx.dataDir, 'config.json')) ? `; your API key file ${path.join(ctx.dataDir, 'config.json')} is kept ("genesis-set config unset-key" clears it)` : ''),
543
+ );
544
+ return 0;
545
+ }
546
+
547
+ function configFileMode(file) {
548
+ if (process.platform === 'win32') return null;
549
+ try {
550
+ return fs.statSync(file).mode & 0o777;
551
+ } catch {
552
+ return null;
553
+ }
554
+ }
555
+
556
+ /** Prints what is installed where, both versions and whether they fit. Exit 1 when something is wrong. */
557
+ export function doctor(ctx) {
558
+ const say = ctx.out;
559
+ const detected = detectAgents(ctx);
560
+ const manifest = readManifest(ctx);
561
+ const problems = [];
562
+ say(`genesis-set ${ctx.version} (this package)`);
563
+ say(`data folder: ${ctx.dataDir}`);
564
+ if (manifest) {
565
+ const ok = manifest.corpus && exists(manifest.corpus);
566
+ say(`corpus: ${manifest.version} at ${manifest.corpus}${ok ? '' : ' (MISSING)'}`);
567
+ if (!ok) problems.push(`corpus folder ${manifest.corpus} is missing`);
568
+ if (manifest.version !== ctx.version) say(`note: installed ${manifest.version}, this package is ${ctx.version}; run "genesis-set update"`);
569
+ } else {
570
+ say('corpus: not installed (run "genesis-set install")');
571
+ }
572
+ const st = mindSetState(ctx);
573
+ const range = ctx.mindSetRange ?? 'any';
574
+ const verdict = {
575
+ ok: 'compatible',
576
+ missing: 'NOT INSTALLED',
577
+ old: 'INCOMPATIBLE (older; "genesis-set update" updates it)',
578
+ incompatible: 'INCOMPATIBLE',
579
+ }[st.state];
580
+ say(`mind-set: ${st.version ?? 'not installed'} at ${ctx.mindSetDir}; genesis-set needs ${range}: ${verdict}`);
581
+ if (st.state !== 'ok') problems.push(`mind-set ${st.version ?? 'is missing'}: genesis-set ${ctx.version} needs ${range}`);
582
+ const bundled = bundledMindSet(ctx);
583
+ say(`mind-set package shipped with genesis-set: ${bundled ? `${bundled.version} (${bundled.dir})` : 'not found'}`);
584
+ if (manifest && !exists(mindSetCorpus(ctx))) problems.push(`the mind-set corpus ${mindSetCorpus(ctx)} the skills point at is missing`);
585
+ const settings = resolveSettings(ctx.env);
586
+ say(
587
+ `Genesis Compiler API key: ${settings.apiKey ? `set (from ${settings.keySource})` : `not set (${API_KEY_ENV}, or "genesis-set config set-key"; create one at ${portalKeysUrl(settings.apiBase)})`}; ` +
588
+ 'its value is never printed',
589
+ );
590
+ say(`Genesis Compiler API base: ${settings.apiBase} (${settings.baseSource})`);
591
+ for (const p of settings.problems) problems.push(p);
592
+ const cfgMode = configFileMode(settings.configFile);
593
+ if (cfgMode !== null && (cfgMode & 0o077) !== 0) {
594
+ problems.push(`${settings.configFile} is readable by other users (mode ${cfgMode.toString(8)}); run "chmod 600 ${settings.configFile}"`);
595
+ }
596
+ if (manifest?.mcp) {
597
+ const ok = exists(mcpServerFile(ctx));
598
+ say(`MCP server: ${mcpServerFile(ctx)}${ok ? '' : ' (MISSING)'}`);
599
+ if (!ok) problems.push(`the MCP server ${mcpServerFile(ctx)} is missing`);
600
+ } else {
601
+ say('MCP server: not installed (run "genesis-set install")');
602
+ }
603
+ say('agents:');
604
+ for (const name of ['claude', 'codex']) {
605
+ const agent = ctx.agents[name];
606
+ const how = detected[name] ? `detected (${detected[name]})` : 'not detected';
607
+ say(` ${agent.label}: ${how}; skills folder ${agent.skillsDir}`);
608
+ const ours = [];
609
+ const theirs = [];
610
+ try {
611
+ for (const d of fs.readdirSync(agent.skillsDir, { withFileTypes: true })) {
612
+ if (!d.isDirectory()) continue;
613
+ const dir = path.join(agent.skillsDir, d.name);
614
+ const g = readMarker(dir);
615
+ if (g) ours.push(`${d.name} (${g.version})`);
616
+ const m = readMarker(dir, MIND_SET_MARKER, 'mind-set');
617
+ if (m) theirs.push(`${d.name} (${m.version})`);
618
+ }
619
+ } catch {
620
+ // no skills folder
621
+ }
622
+ say(` genesis-set skills: ${ours.length ? ours.sort().join(', ') : 'none'}`);
623
+ say(` mind-set skills: ${theirs.length ? theirs.sort().join(', ') : 'none'}`);
624
+ const reg = REGISTRATION[name](ctx);
625
+ say(` MCP server "genesis": ${reg}`);
626
+ if (manifest?.mcp?.agents?.[name] && reg !== 'registered') problems.push(`${agent.label}: the genesis MCP server is ${reg}`);
627
+ for (const s of manifest?.agents?.[name]?.skills ?? []) {
628
+ if (!readMarker(path.join(agent.skillsDir, s))) problems.push(`${agent.label} skill ${s} is in the manifest but missing or replaced`);
629
+ }
630
+ if (manifest?.agents?.[name] && theirs.length === 0) problems.push(`${agent.label} has genesis-set skills but no mind-set skills`);
631
+ }
632
+ if (problems.length) {
633
+ say('problems:');
634
+ for (const p of problems) say(` - ${p}`);
635
+ say('run "genesis-set install" (or "genesis-set update") to repair');
636
+ return 1;
637
+ }
638
+ return 0;
639
+ }