@evomap/evolver-cli 2.0.53 → 2.0.55

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.
@@ -5,4 +5,6 @@ export type ContainedWriteResult = {
5
5
  reason: 'exists' | 'unsafe_path';
6
6
  };
7
7
  export declare function relativePathInsideRoot(root: string, requested: string): string | null;
8
- export declare function writeFileInsideRoot(root: string, relPath: string, content: string, overwrite: boolean): ContainedWriteResult;
8
+ export declare function writeFileInsideRoot(root: string, relPath: string, content: string | Uint8Array, overwrite: boolean): ContainedWriteResult;
9
+ /** What `writeFileInsideRoot` would answer for this target, decided without creating or changing anything. */
10
+ export declare function checkWriteInsideRoot(root: string, relPath: string, overwrite: boolean): ContainedWriteResult;
@@ -22,6 +22,26 @@ export function writeFileInsideRoot(root, relPath, content, overwrite) {
22
22
  }
23
23
  return writeRegularFile(join(dir, fileName), content, overwrite);
24
24
  }
25
+ /** What `writeFileInsideRoot` would answer for this target, decided without creating or changing anything. */
26
+ export function checkWriteInsideRoot(root, relPath, overwrite) {
27
+ const parts = relPath.split(sep).filter((part) => part && part !== '.');
28
+ const fileName = parts.pop();
29
+ if (!fileName || parts.includes('..'))
30
+ return { ok: false, reason: 'unsafe_path' };
31
+ let dir = resolve(root);
32
+ for (const part of parts) {
33
+ dir = join(dir, part);
34
+ const stat = lstatOrNull(dir);
35
+ if (!stat)
36
+ return { ok: true };
37
+ if (!stat.isDirectory() || stat.isSymbolicLink())
38
+ return { ok: false, reason: 'unsafe_path' };
39
+ }
40
+ const existing = lstatOrNull(join(dir, fileName));
41
+ if (existing && !isUnsharedRegularFile(existing))
42
+ return { ok: false, reason: 'unsafe_path' };
43
+ return existing && !overwrite ? { ok: false, reason: 'exists' } : { ok: true };
44
+ }
25
45
  function ensureRealDirectory(path) {
26
46
  if (!lstatOrNull(path)) {
27
47
  try {
package/dist/lifecycle.js CHANGED
@@ -191,18 +191,25 @@ async function runLifecycleCommandInner(argv, deps) {
191
191
  case 'start': {
192
192
  const result = await startLifecycle(paths, env);
193
193
  stdout(`${JSON.stringify(result)}\n`);
194
- return 0;
194
+ if (!isUnmanagedProxy(result))
195
+ return 0;
196
+ stderr(unmanagedProxyHint(result));
197
+ return 1;
195
198
  }
196
199
  case 'stop': {
197
200
  const result = stopLifecycle(paths);
198
201
  stdout(`${JSON.stringify(result)}\n`);
202
+ if (isUnmanagedProxy(result))
203
+ stderr(unmanagedProxyHint(result));
199
204
  return 0;
200
205
  }
201
206
  case 'restart': {
202
- stopLifecycle(paths);
203
- const result = await startLifecycle(paths, env);
207
+ const result = await restartLifecycle(paths, env);
204
208
  stdout(`${JSON.stringify({ ...result, status: result.status === 'started' ? 'restarted' : result.status })}\n`);
205
- return 0;
209
+ if (!isUnmanagedProxy(result))
210
+ return 0;
211
+ stderr(unmanagedProxyHint(result));
212
+ return 1;
206
213
  }
207
214
  case 'status': {
208
215
  const status = await lifecycleStatus(paths, env);
@@ -214,9 +221,12 @@ async function runLifecycleCommandInner(argv, deps) {
214
221
  stdout(`${JSON.stringify(status, null, 2)}\n`);
215
222
  if (!status.healthy) {
216
223
  stderr(`[Lifecycle] unhealthy reason=${status.reason ?? 'unknown'}; restarting\n`);
217
- stopLifecycle(paths);
218
- const result = await startLifecycle(paths, env);
224
+ const result = await restartLifecycle(paths, env);
219
225
  stdout(`${JSON.stringify(result)}\n`);
226
+ if (isUnmanagedProxy(result)) {
227
+ stderr(unmanagedProxyHint(result));
228
+ return 1;
229
+ }
220
230
  const next = await lifecycleStatus(paths, env);
221
231
  stdout(`${JSON.stringify({ after_restart: lifecycleStatusForOperator(next), log: 'inspect EVOLVER_LIFECYCLE_LOG_FILE or EVOLVER_LIFECYCLE_LOG_DIR' }, null, 2)}\n`);
222
232
  if (!next.healthy) {
@@ -482,6 +492,9 @@ export async function startLifecycle(paths, env = process.env) {
482
492
  stopLifecycle(paths);
483
493
  else
484
494
  rmSync(paths.pidFile, { force: true });
495
+ const unmanaged = unmanagedProxyResult(paths.settingsFile);
496
+ if (unmanaged)
497
+ return unmanaged;
485
498
  const command = resolveDaemonCommand(env);
486
499
  const cwd = env['EVOLVER_LIFECYCLE_CWD'] || process.cwd();
487
500
  const out = openSync(paths.logFile, 'a');
@@ -515,12 +528,36 @@ function oneShotChildEnv(env) {
515
528
  delete childEnv['EVOLVER_SELF_UPDATE_SUPERVISOR'];
516
529
  return childEnv;
517
530
  }
531
+ const PROXY_NOT_STARTED_BY_LIFECYCLE = 'proxy_not_started_by_lifecycle';
532
+ function isUnmanagedProxy(result) {
533
+ return result.reason === PROXY_NOT_STARTED_BY_LIFECYCLE;
534
+ }
535
+ function unmanagedProxyHint(result) {
536
+ return `[Lifecycle] proxy pid ${result.pid} was not started by \`evolver lifecycle start\`, so lifecycle will neither stop nor replace it; it is owned by the installed service or a foreground \`evolver proxy\`. Remove the service with \`evolver lifecycle remove-service\`, or stop its owner directly.\n`;
537
+ }
538
+ function unmanagedProxyResult(settingsFile) {
539
+ const pid = livePublishingProxyPid(readProxySettings(settingsFile, { quietReadError: true }));
540
+ return pid ? { status: 'not_owned', pid, reason: PROXY_NOT_STARTED_BY_LIFECYCLE } : undefined;
541
+ }
542
+ function livePublishingProxyPid({ pid, startedAt }) {
543
+ if (!pid || !startedAt || !isPidRunning(pid))
544
+ return undefined;
545
+ const processStartedAt = processStartedAtMs(pid);
546
+ // A reused pid belongs to a process born after the proxy that published started_at.
547
+ return processStartedAt !== undefined && processStartedAt <= Date.parse(startedAt) ? pid : undefined;
548
+ }
549
+ async function restartLifecycle(paths, env) {
550
+ const stopped = stopLifecycle(paths);
551
+ if (isUnmanagedProxy(stopped))
552
+ return stopped;
553
+ return startLifecycle(paths, env);
554
+ }
518
555
  export function stopLifecycle(paths, deps = {}) {
519
556
  const pidFile = readPidFile(paths.pidFile);
520
557
  const pid = pidFile.pid;
521
558
  if (!pid || !isPidRunning(pid)) {
522
559
  rmSync(paths.pidFile, { force: true });
523
- return { status: 'not_running' };
560
+ return unmanagedProxyResult(paths.settingsFile) ?? { status: 'not_running' };
524
561
  }
525
562
  if (!pidFile.owned || !waitForPidFileRecordMatch(pidFile, 1_000, deps.processCommandLine ?? processCommandLine, deps.processIdentity ?? processIdentity, deps.platform ?? process.platform)) {
526
563
  return { status: 'not_owned', pid, reason: 'pidfile_owner_unconfirmed' };
@@ -5158,8 +5195,7 @@ async function runWatch(paths, env, flags, stdout, stderr) {
5158
5195
  }
5159
5196
  else {
5160
5197
  stdout(`[Watch] ${new Date().toISOString()} unhealthy reason=${status.reason ?? 'unknown'} restarting...\n`);
5161
- stopLifecycle(paths);
5162
- const result = await startLifecycle(paths, env);
5198
+ const result = await restartLifecycle(paths, env);
5163
5199
  stdout(`[Watch] restart result: ${JSON.stringify(result)}\n`);
5164
5200
  skippedLastTick = false;
5165
5201
  }
@@ -5413,6 +5449,21 @@ function processIdentity(pid) {
5413
5449
  }
5414
5450
  return undefined;
5415
5451
  }
5452
+ function processStartedAtMs(pid) {
5453
+ if (process.platform === 'win32')
5454
+ return processIdentity(pid)?.startedAt;
5455
+ try {
5456
+ const startedAt = Date.parse(execFileSync(PS_PATH, ['-p', String(pid), '-o', 'lstart='], {
5457
+ encoding: 'utf8',
5458
+ env: { ...process.env, LANG: 'C', LC_ALL: 'C' },
5459
+ stdio: ['ignore', 'pipe', 'ignore'],
5460
+ }).trim());
5461
+ return Number.isFinite(startedAt) ? startedAt : undefined;
5462
+ }
5463
+ catch {
5464
+ return undefined;
5465
+ }
5466
+ }
5416
5467
  function processIdentityMatchesRecord(record, identity) {
5417
5468
  if (!identity?.executable || !identity.parentPid || !identity.startedAt)
5418
5469
  return false;
package/dist/recipe.js CHANGED
@@ -16,6 +16,8 @@ const MAX_RECIPE_STEPS = 20;
16
16
  const MAX_RECIPE_VALIDATION_COMMANDS = 5;
17
17
  const MAX_RECIPE_INPUT_BYTES = 1024 * 1024;
18
18
  const MAX_ID_LENGTH = 200;
19
+ /** The running proxy's Hub auth state in the shared store (`proxyDaemon` HUB_AUTH_STATUS_STATE_KEY). */
20
+ const PROXY_HUB_AUTH_STATUS = 'hub:auth_status';
19
21
  const SENSITIVE_ERROR_KEYS = new Set(['authorization', 'node_secret', 'nodesecret', 'token', 'access_token', 'refresh_token', 'secret']);
20
22
  const STALE_NODE_SECRET_ERRORS = new Set(['node_secret_invalid', 'node_secret_not_set']);
21
23
  const RECIPE_SEARCH_VALUE_OPTIONS = new Set(['--q', '--query', '--limit']);
@@ -1427,12 +1429,19 @@ function persistRotatedNodeSecret(secret, version, nodeId, env, legacyDir) {
1427
1429
  const storePath = recipeProxyStorePath(env);
1428
1430
  const store = new mailbox.MailboxStore({ path: storePath });
1429
1431
  try {
1432
+ const proxyNodeId = store.getState('node_id')?.trim();
1430
1433
  store.setState('node_secret_source', 'pending_rotate');
1431
1434
  if (nodeId)
1432
1435
  store.setState('node_id', nodeId);
1433
1436
  store.setState('node_secret', secret);
1434
1437
  setOptionalStoreState(store, 'node_secret_version', version !== undefined ? String(version) : undefined);
1435
1438
  store.setState('node_secret_source', 'hub_rotate');
1439
+ // A running proxy refuses Hub calls while it records an auth failure; the new secret is what that failure
1440
+ // waited for, so lift it and let the proxy's next request present the secret it now reloads from this store.
1441
+ // The proxy reloads only its own node's secret, so a rotation of another node leaves its failure standing.
1442
+ const sameNode = !nodeId || !proxyNodeId || nodeId === proxyNodeId;
1443
+ if (sameNode && store.getState(PROXY_HUB_AUTH_STATUS) === 'auth_failed')
1444
+ store.setState(PROXY_HUB_AUTH_STATUS, '');
1436
1445
  }
1437
1446
  finally {
1438
1447
  store.close();
package/dist/reuse.js CHANGED
@@ -11,7 +11,7 @@
11
11
  // 1. Print EXACTLY ONE envelope object to STDOUT on BOTH success and failure (in --json mode).
12
12
  // 2. NEVER let a token/secret reach any stream — error text is mapped to fixed messages / redacted.
13
13
  import { assetrepair, assetstore, events, hub as hubNs, wire } from '@evomap/evolver-core';
14
- import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled, stripHubDeliveryMetadataForIntegrity, } from '@evomap/evolver-adapter-public';
14
+ import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubAntiAbuseBlock, isHubDryRunEnabled, stripHubDeliveryMetadataForIntegrity, } from '@evomap/evolver-adapter-public';
15
15
  import { loadEnvFileFromEnv, proxyClientFromEnv } from '@evomap/evolver-mcp';
16
16
  import { createRecipeHubFromEnv } from './recipe.js';
17
17
  import { getCliVersion } from './version.js';
@@ -469,15 +469,6 @@ const ANTI_ABUSE_BLOCK_MESSAGE = 'hub anti-abuse temporarily blocked asset fetch
469
469
  function antiAbuseOutcome() {
470
470
  return { ok: false, status: 'rate_limited', message: ANTI_ABUSE_BLOCK_MESSAGE };
471
471
  }
472
- function isAntiAbuseFetchBlock(status, code) {
473
- return status === 403 && code !== undefined && /antibody|bulk_fetch|anti[-_]?abuse/i.test(code);
474
- }
475
- function hubErrorField(body) {
476
- if (!body || typeof body !== 'object')
477
- return undefined;
478
- const err = body['error'];
479
- return typeof err === 'string' ? err : undefined;
480
- }
481
472
  function recordValue(value) {
482
473
  return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
483
474
  }
@@ -492,7 +483,7 @@ function mapError(e) {
492
483
  // hubFetch raises AuthError for BOTH 401 and 403, so the hub's anti-abuse 403
493
484
  // (`bulk_fetch_blocked: IP antibody active`) used to be misreported as "log in" — it is an
494
485
  // abuse-control block on a perfectly healthy credential, not an auth failure (#555).
495
- if (isAntiAbuseFetchBlock(e.status, e.errorCode))
486
+ if (isHubAntiAbuseBlock(e))
496
487
  return antiAbuseOutcome();
497
488
  return { ok: false, status: 'unauthorized', message: 'hub authentication failed; run `evolver login` or set EVOMAP_NODE_SECRET' };
498
489
  }
@@ -501,7 +492,7 @@ function mapError(e) {
501
492
  if (e instanceof HubClientError) {
502
493
  if (e.status === 429)
503
494
  return { ok: false, status: 'rate_limited', message: 'hub rate limited the request; retry later' };
504
- if (isAntiAbuseFetchBlock(e.status, hubErrorField(e.body)))
495
+ if (isHubAntiAbuseBlock(e))
505
496
  return antiAbuseOutcome();
506
497
  if (e.status === 401 || e.status === 403)
507
498
  return { ok: false, status: 'unauthorized', message: 'hub authentication failed; run `evolver login` or set EVOMAP_NODE_SECRET' };
@@ -67,6 +67,10 @@ export declare function runSkillDistill(argv: readonly string[], injected?: Part
67
67
  */
68
68
  export declare function geneToSkillMd(gene: Record<string, unknown>, opts?: {
69
69
  name?: string;
70
+ requiredSkills?: readonly {
71
+ name: string;
72
+ path: string;
73
+ }[];
70
74
  }): string;
71
75
  /**
72
76
  * `evolver skill-md-update --gene <id> --skill <SKILL.md|dir> [--dry-run]` (B4).
@@ -272,6 +272,10 @@ export function geneToSkillMd(gene, opts = {}) {
272
272
  }
273
273
  if (preconditions.length)
274
274
  out.push('## Preconditions', '', ...preconditions.map((p) => `- ${p}`), '');
275
+ if (opts.requiredSkills && opts.requiredSkills.length > 0) {
276
+ out.push('## Required Skills', '', 'Installed next to this skill. Read each one before following the strategy.', '');
277
+ out.push(...opts.requiredSkills.map((skill) => `- \`${skill.name}\`: [${skill.path}](${skill.path})`), '');
278
+ }
275
279
  if (strategy.length)
276
280
  out.push('## Strategy', '', ...strategy.map((s, i) => `${i + 1}. ${s}`), '');
277
281
  if (avoid.length)
@@ -1,5 +1,7 @@
1
- import { assetstore, type hub as hubNs } from '@evomap/evolver-core';
1
+ import { assetstore, skill, type hub as hubNs } from '@evomap/evolver-core';
2
2
  import type { ConnectPublicOptions, PublicHubCapability } from '@evomap/evolver-adapter-public';
3
+ type RequiredSkillRef = skill.RequiredSkillRef;
4
+ type Result<T> = skill.Result<T>;
3
5
  export interface SkillFetchHub {
4
6
  search(query: assetstore.SearchQuery): Promise<assetstore.AssetRecord[]>;
5
7
  fetch(query: assetstore.SearchQuery): Promise<assetstore.AssetRecord[]>;
@@ -15,5 +17,8 @@ export interface SkillFetchDeps {
15
17
  hub: PublicHubCapability;
16
18
  auth: hubNs.AuthProvider;
17
19
  };
20
+ /** Fetches a required skill's files, and the commit they come from, from its git repository; the network boundary of an install. */
21
+ fetchSkillFiles?: (ref: RequiredSkillRef) => Result<skill.FetchedSkill> | Promise<Result<skill.FetchedSkill>>;
18
22
  }
19
- export declare function runSkillCommand(argv: readonly string[], deps?: SkillFetchDeps): Promise<number>;
23
+ export declare function runSkillCommand(argv: readonly string[], deps?: SkillFetchDeps): Promise<number>;
24
+ export {};
@@ -1,10 +1,12 @@
1
- import { join } from 'node:path';
2
- import { assetstore, wire } from '@evomap/evolver-core';
3
- import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled, } from '@evomap/evolver-adapter-public';
1
+ import { lstatSync, readdirSync } from 'node:fs';
2
+ import { join, sep } from 'node:path';
3
+ import { assetstore, skill, wire } from '@evomap/evolver-core';
4
+ import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled, stripHubDeliveryMetadataForIntegrity, } from '@evomap/evolver-adapter-public';
4
5
  import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
5
- import { relativePathInsideRoot, writeFileInsideRoot } from './containedWrite.js';
6
+ import { checkWriteInsideRoot, relativePathInsideRoot, writeFileInsideRoot } from './containedWrite.js';
6
7
  import { createRecipeHubFromEnv } from './recipe.js';
7
8
  import { geneToSkillMd } from './skillDistill.js';
9
+ const { checkSkillTree, digestOfSkillFiles, fetchSkillFiles, requiredSkillsOf } = skill;
8
10
  const GROUP = 'skill.fetch';
9
11
  const DEFAULT_LIMIT = 5;
10
12
  const MAX_LIMIT = 20;
@@ -14,27 +16,6 @@ const USAGE = [
14
16
  ' evolver skill fetch --signals <s1,s2> [--limit N] [--select <asset_id_or_gene_id>] [--out <dir>] [--write] [--force] [--json]',
15
17
  ' evolver skill fetch --query <text> [--limit N] [--select <asset_id_or_gene_id>] [--out <dir>] [--write] [--force] [--json]',
16
18
  ].join('\n');
17
- const HUB_METADATA_KEYS = new Set([
18
- 'credit_cost',
19
- 'gdi_score',
20
- 'success_rate',
21
- 'reuse_count',
22
- 'ranking_score',
23
- 'source_node_id',
24
- 'fetched_at',
25
- 'receipt',
26
- 'hub_receipt',
27
- 'already_purchased',
28
- '_semantic_similarity',
29
- 'semantic_similarity',
30
- '_search_score',
31
- 'search_score',
32
- '_match_score',
33
- 'match_score',
34
- '_retrieval_rank',
35
- 'retrieval_rank',
36
- 'original_asset_id',
37
- ]);
38
19
  export async function runSkillCommand(argv, deps = {}) {
39
20
  const sub = argv[0];
40
21
  if (sub === 'fetch')
@@ -66,7 +47,7 @@ async function runSkillFetchCommand(argv, deps = {}) {
66
47
  return 0;
67
48
  }
68
49
  const hub = deps.hub ?? createSkillFetchHubFromEnv(deps, env);
69
- const run = await buildSkillFetchResult(hub, opts, cwd);
50
+ const run = await buildSkillFetchResult(hub, opts, cwd, deps.fetchSkillFiles ?? fetchSkillFiles);
70
51
  if (!run.ok)
71
52
  return emitFailure(run.reason, run.message, opts.json, io);
72
53
  emitSuccess(run.value, opts.json, io);
@@ -128,7 +109,7 @@ function parseSkillFetchArgs(argv, cwd) {
128
109
  },
129
110
  };
130
111
  }
131
- async function buildSkillFetchResult(hub, opts, cwd) {
112
+ async function buildSkillFetchResult(hub, opts, cwd, fetchFiles) {
132
113
  const direct = opts.source.kind === 'asset' ? await fetchGeneById(hub, opts.source.id) : null;
133
114
  if (direct && !direct.ok)
134
115
  return direct;
@@ -158,7 +139,7 @@ async function buildSkillFetchResult(hub, opts, cwd) {
158
139
  if (selected.asset.asset_id !== previewed.assetId) {
159
140
  return { ok: false, reason: 'integrity_error', message: 'selected Gene asset_id changed after preview' };
160
141
  }
161
- const written = writeSkill(selected.asset, cwd, opts.outDir, opts.force);
142
+ const written = await writeSkill(selected.asset, cwd, opts.outDir, opts.force, fetchFiles);
162
143
  if (!written.ok)
163
144
  return written;
164
145
  return { ok: true, value: { mode: 'write', candidates: [candidateFromGene(selected.asset, opts.outDir)], written: written.value } };
@@ -200,7 +181,7 @@ async function fetchGeneById(hub, id) {
200
181
  function normalizeRemoteGene(asset, requestedId) {
201
182
  if (asset.type !== 'Gene')
202
183
  return { ok: false, reason: 'unsupported', message: `skill fetch only supports Gene assets, got ${asset.type}` };
203
- const cleaned = stripHubMetadata(asset);
184
+ const cleaned = stripHubDeliveryMetadataForIntegrity(asset);
204
185
  const claimed = stringField(cleaned, 'asset_id');
205
186
  if (!claimed)
206
187
  return { ok: false, reason: 'integrity_error', message: 'remote Gene is missing asset_id' };
@@ -213,6 +194,9 @@ function normalizeRemoteGene(asset, requestedId) {
213
194
  if (!isContentAssetId(requestedId) && stringField(cleaned, 'id') !== requestedId)
214
195
  return { ok: false, reason: 'integrity_error', message: 'remote Gene id does not match requested id' };
215
196
  }
197
+ const required = requiredSkillsOf(cleaned);
198
+ if (!required.ok)
199
+ return { ok: false, reason: 'unsupported', message: `Gene ${required.message}` };
216
200
  return { ok: true, asset: cleaned };
217
201
  }
218
202
  function candidateFromGene(gene, outDir) {
@@ -230,22 +214,104 @@ function candidateFromGene(gene, outDir) {
230
214
  candidate.summary = summary;
231
215
  if (outDir)
232
216
  candidate.target = relativeSkillPath(name);
217
+ const required = requiredSkillsOf(gene);
218
+ if (required.ok && required.value.length > 0)
219
+ candidate.requiredSkills = required.value;
233
220
  return candidate;
234
221
  }
235
- function writeSkill(gene, cwd, outDir, force) {
222
+ async function writeSkill(gene, cwd, outDir, force, fetchFiles) {
236
223
  const name = skillNameForGene(gene);
237
224
  const target = relativeSkillPath(name);
238
- const write = writeFileInsideRoot(cwd, join(outDir, target), geneToSkillMd(gene, { name }), force);
239
- if (!write.ok && write.reason === 'exists')
240
- return { ok: false, reason: 'conflict', message: `SKILL.md already exists for skill ${name}; use --force to overwrite` };
241
- if (!write.ok)
242
- return { ok: false, reason: 'invalid_arg', message: 'skill target path must not pass through a symlink, junction, hard link, or non-directory' };
225
+ const required = await planRequiredSkills(gene, name, fetchFiles);
226
+ if (!required.ok)
227
+ return required;
228
+ const skillMd = geneToSkillMd(gene, {
229
+ name,
230
+ requiredSkills: required.value.map(({ skill }) => ({ name: skill.name, path: `../${skill.name}/SKILL.md` })),
231
+ });
232
+ // The Gene's own SKILL.md goes last: its presence then means everything it points at is already on disk.
233
+ const planned = [...required.value.flatMap((plan) => plan.planned), { target, content: skillMd }];
234
+ if (required.value.length > 0) {
235
+ const blocked = installBlocker(cwd, outDir, planned, required.value.map((plan) => plan.skill.name), force);
236
+ if (blocked)
237
+ return blocked;
238
+ }
239
+ for (const file of planned) {
240
+ const write = writeFileInsideRoot(cwd, join(outDir, ...file.target.split('/')), file.content, force);
241
+ if (!write.ok && write.reason === 'exists')
242
+ return { ok: false, reason: 'conflict', message: `SKILL.md already exists for skill ${name}; use --force to overwrite` };
243
+ if (!write.ok)
244
+ return { ok: false, reason: 'invalid_arg', message: 'skill target path must not pass through a symlink, junction, hard link, or non-directory' };
245
+ }
243
246
  const written = { target, assetId: gene.asset_id, name };
244
247
  const geneId = stringField(gene, 'id');
245
248
  if (geneId)
246
249
  written.geneId = geneId;
250
+ if (required.value.length > 0)
251
+ written.requiredSkills = required.value.map((plan) => plan.skill);
247
252
  return { ok: true, value: written };
248
253
  }
254
+ /**
255
+ * Decide before the first write whether the whole install can land: every target writable, and each skill
256
+ * directory free of files the pinned skill does not have, so what is on disk afterwards is exactly the pinned
257
+ * content. Leftovers are refused, not deleted: they may be the user's.
258
+ */
259
+ function installBlocker(cwd, outDir, planned, skillNames, force) {
260
+ const pathOf = (target) => join(outDir, ...target.split('/'));
261
+ for (const file of planned) {
262
+ const check = checkWriteInsideRoot(cwd, pathOf(file.target), force);
263
+ if (!check.ok && check.reason === 'exists')
264
+ return { ok: false, reason: 'conflict', message: `${file.target} already exists; use --force to overwrite. Nothing was written` };
265
+ if (!check.ok)
266
+ return { ok: false, reason: 'invalid_arg', message: 'skill target path must not pass through a symlink, junction, hard link, or non-directory. Nothing was written' };
267
+ }
268
+ const expected = new Set(planned.map((file) => file.target));
269
+ for (const name of skillNames) {
270
+ const stray = filesUnder(join(cwd, pathOf(`skills/${name}`)), `skills/${name}`).find((target) => !expected.has(target));
271
+ if (stray)
272
+ return { ok: false, reason: 'conflict', message: `${stray} is not part of the pinned skill; remove skills/${name} and retry. Nothing was written` };
273
+ }
274
+ return null;
275
+ }
276
+ function filesUnder(dir, target) {
277
+ let stat;
278
+ try {
279
+ stat = lstatSync(dir);
280
+ }
281
+ catch {
282
+ return [];
283
+ }
284
+ if (!stat.isDirectory())
285
+ return [target];
286
+ return readdirSync(dir).flatMap((entry) => filesUnder(`${dir}${sep}${entry}`, `${target}/${entry}`));
287
+ }
288
+ /**
289
+ * Fetch every skill the Gene requires and check it before a single file is written: against the Gene's pin, or, for a
290
+ * skill that follows a branch, record the commit and digest it resolved to so the install can be reproduced.
291
+ */
292
+ async function planRequiredSkills(gene, geneSkillName, fetchFiles) {
293
+ const declared = requiredSkillsOf(gene);
294
+ const plans = [];
295
+ for (const ref of declared.ok ? declared.value : []) {
296
+ const refuse = (why) => ({ ok: false, reason: 'required_skill', message: `required skill ${ref.name} cannot be installed: ${why}. Nothing was written` });
297
+ if (ref.name === safeSkillName(geneSkillName))
298
+ return refuse('its directory name collides with the skill rendered from this Gene');
299
+ const fetched = await fetchFiles(ref);
300
+ if (!fetched.ok)
301
+ return refuse(fetched.message);
302
+ const { commit, files } = fetched.value;
303
+ const tree = checkSkillTree(files.map((file) => ({ mode: '100644', type: 'blob', size: file.content.length, path: file.path })));
304
+ if (!tree.ok)
305
+ return refuse(tree.message);
306
+ const sha256 = digestOfSkillFiles(files);
307
+ if ('sha256' in ref && sha256 !== ref.sha256)
308
+ return refuse('its content does not match the sha256 the Gene pins');
309
+ const resolved = 'branch' in ref ? { ...ref, commit, sha256 } : ref;
310
+ const planned = files.map((file) => ({ target: `skills/${ref.name}/${file.path}`, content: file.content }));
311
+ plans.push({ skill: { ...resolved, target: `skills/${ref.name}/SKILL.md`, files: planned.map((file) => file.target) }, planned });
312
+ }
313
+ return { ok: true, value: plans };
314
+ }
249
315
  function createSkillFetchHubFromEnv(deps, env = deps.env ?? process.env) {
250
316
  return createRecipeHubFromEnv(env, deps.connectHub ?? connectPublicHub);
251
317
  }
@@ -263,10 +329,15 @@ function emitSuccess(value, json, io) {
263
329
  const gene = c.geneId ? ` gene=${c.geneId}` : '';
264
330
  const signals = c.signals.length > 0 ? ` signals=${c.signals.join(',')}` : '';
265
331
  const target = c.target ? ` target=${c.target}` : '';
266
- io.stdout(` ${c.assetId}${gene} name=${c.name}${signals}${target}`);
332
+ const requires = c.requiredSkills ? ` requires=${c.requiredSkills.map((skill) => skill.name).join(',')}` : '';
333
+ io.stdout(` ${c.assetId}${gene} name=${c.name}${signals}${target}${requires}`);
267
334
  if (c.summary)
268
335
  io.stdout(` ${c.summary}`);
269
336
  }
337
+ for (const skill of value.written?.requiredSkills ?? []) {
338
+ const source = skill.branch ? `${skill.repo} branch ${skill.branch} at ${skill.commit} (sha256 ${skill.sha256})` : `${skill.repo}@${skill.commit.slice(0, 12)}`;
339
+ io.stdout(`skill fetch: installed required skill ${skill.name} (${skill.files.length} file(s)) from ${source}`);
340
+ }
270
341
  if (value.written)
271
342
  io.stdout(`skill fetch: wrote ${value.written.target}`);
272
343
  }
@@ -339,13 +410,6 @@ function flagValue(args, flag) {
339
410
  function splitList(value) {
340
411
  return value.split(',').map((item) => item.trim()).filter(Boolean);
341
412
  }
342
- function stripHubMetadata(asset) {
343
- const out = {};
344
- for (const [key, value] of Object.entries(asset))
345
- if (!HUB_METADATA_KEYS.has(key))
346
- out[key] = value;
347
- return out;
348
- }
349
413
  function skillNameForGene(gene) {
350
414
  const signals = arrayOfStrings(gene['signals_match']).slice(0, 4).join('-');
351
415
  const raw = signals || stringField(gene, 'id') || gene.asset_id.replace(/^sha256:/, '').slice(0, 12);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evomap/evolver-cli",
3
- "version": "2.0.53",
3
+ "version": "2.0.55",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {
@@ -27,12 +27,12 @@
27
27
  }
28
28
  },
29
29
  "dependencies": {
30
- "@evomap/evolver-core": "2.0.53",
31
- "@evomap/evolver-adapter-public": "2.0.53",
32
- "@evomap/evolver-mcp": "2.0.53",
33
- "@evomap/evolver-proxy": "2.0.53",
34
- "@evomap/evolver-runtime-adapters": "2.0.53",
35
- "@evomap/evolver-webui": "2.0.53"
30
+ "@evomap/evolver-core": "2.0.55",
31
+ "@evomap/evolver-adapter-public": "2.0.55",
32
+ "@evomap/evolver-mcp": "2.0.55",
33
+ "@evomap/evolver-proxy": "2.0.55",
34
+ "@evomap/evolver-runtime-adapters": "2.0.55",
35
+ "@evomap/evolver-webui": "2.0.55"
36
36
  },
37
37
  "repository": {
38
38
  "type": "git",