@evomap/evolver-cli 2.0.53 → 2.0.54

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 {
@@ -0,0 +1,10 @@
1
+ import { type RequiredSkillRef, type Result, type SkillFile } from './requiredSkills.js';
2
+ type SkillSource = Pick<RequiredSkillRef, 'repo' | 'commit' | 'path'>;
3
+ /**
4
+ * Fetch one commit of a public https repository and read a skill directory out of it. Nothing is checked out:
5
+ * files are read from git objects, so repository filters, hooks, symlinks and submodules never touch the disk.
6
+ */
7
+ export declare function fetchSkillFiles(source: SkillSource): Result<SkillFile[]>;
8
+ /** Read the regular files under `path` at `commit` from a local repository that already has the commit. */
9
+ export declare function readSkillTree(repoDir: string, commit: string, path: string): Result<SkillFile[]>;
10
+ export {};
@@ -0,0 +1,67 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { mkdtempSync, rmSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { checkSkillTree } from './requiredSkills.js';
6
+ const FETCH_TIMEOUT_MS = 120_000;
7
+ const MAX_BUFFER = 64 * 1024 * 1024;
8
+ /**
9
+ * Fetch one commit of a public https repository and read a skill directory out of it. Nothing is checked out:
10
+ * files are read from git objects, so repository filters, hooks, symlinks and submodules never touch the disk.
11
+ */
12
+ export function fetchSkillFiles(source) {
13
+ const dir = mkdtempSync(join(tmpdir(), 'evolver-skill-'));
14
+ try {
15
+ git(dir, ['init', '--quiet']);
16
+ git(dir, ['fetch', '--quiet', '--depth', '1', '--no-tags', source.repo, source.commit]);
17
+ return readSkillTree(dir, source.commit, source.path);
18
+ }
19
+ catch (error) {
20
+ return { ok: false, message: `git could not fetch ${source.commit.slice(0, 12)} from ${source.repo} (${gitFailure(error)})` };
21
+ }
22
+ finally {
23
+ rmSync(dir, { recursive: true, force: true });
24
+ }
25
+ }
26
+ /** Read the regular files under `path` at `commit` from a local repository that already has the commit. */
27
+ export function readSkillTree(repoDir, commit, path) {
28
+ let listing;
29
+ try {
30
+ listing = git(repoDir, ['ls-tree', '-r', '-l', '-z', path ? `${commit}:${path}` : commit]);
31
+ }
32
+ catch {
33
+ return { ok: false, message: `the commit has no directory ${JSON.stringify(path || '/')}` };
34
+ }
35
+ const rows = listing.toString('utf8').split('\0').filter(Boolean).map(parseTreeRow);
36
+ const checked = checkSkillTree(rows);
37
+ if (!checked.ok)
38
+ return checked;
39
+ return { ok: true, value: rows.map((row) => ({ path: row.path, content: git(repoDir, ['cat-file', 'blob', row.object]) })) };
40
+ }
41
+ function parseTreeRow(row) {
42
+ const tab = row.indexOf('\t');
43
+ const [mode = '', type = '', object = '', size = ''] = row.slice(0, tab).split(/ +/);
44
+ return { mode, type, object, size: Number(size) || 0, path: row.slice(tab + 1) };
45
+ }
46
+ // https only, no prompts, and neither the user's git configuration nor a caller's GIT_* variables: a hook that
47
+ // exports GIT_DIR, a url.insteadOf rewrite or a credential helper must not change what gets fetched.
48
+ function git(cwd, args) {
49
+ const inherited = Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_'));
50
+ return execFileSync('git', ['-c', 'protocol.allow=never', '-c', 'protocol.https.allow=always', ...args], {
51
+ cwd,
52
+ env: { ...Object.fromEntries(inherited), GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' },
53
+ stdio: ['ignore', 'pipe', 'pipe'],
54
+ timeout: FETCH_TIMEOUT_MS,
55
+ maxBuffer: MAX_BUFFER,
56
+ windowsHide: true,
57
+ });
58
+ }
59
+ function gitFailure(error) {
60
+ const record = error;
61
+ if (record.code === 'ENOENT')
62
+ return 'git is not installed';
63
+ if (record.code === 'ETIMEDOUT')
64
+ return 'timed out';
65
+ const stderr = Buffer.isBuffer(record.stderr) ? record.stderr.toString('utf8') : '';
66
+ return stderr.trim().split('\n').pop()?.slice(0, 200) || 'git failed';
67
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * A skill a Gene needs, pinned to a git commit and to the content of the skill directory. It travels as one
3
+ * `preconditions` entry, so it is covered by the Gene's asset_id and needs no wire-schema field:
4
+ *
5
+ * skill:git+https://github.com/owner/repo@<commit>#sha256=<digest>&path=<dir inside the repo>
6
+ */
7
+ export interface RequiredSkillRef {
8
+ /** Directory the skill is installed under: `skills/<name>/`. */
9
+ name: string;
10
+ repo: string;
11
+ commit: string;
12
+ /** Skill directory inside the repository, POSIX separators; empty for the repository root. */
13
+ path: string;
14
+ sha256: string;
15
+ }
16
+ /** One file of a skill, with its path relative to the skill directory (POSIX separators). */
17
+ export interface SkillFile {
18
+ path: string;
19
+ content: Uint8Array;
20
+ }
21
+ /** One `git ls-tree -r -l` row, with its path relative to the skill directory. */
22
+ export interface SkillTreeEntry {
23
+ mode: string;
24
+ type: string;
25
+ size: number;
26
+ path: string;
27
+ }
28
+ export type Result<T> = {
29
+ ok: true;
30
+ value: T;
31
+ } | {
32
+ ok: false;
33
+ message: string;
34
+ };
35
+ /**
36
+ * Read the skills a Gene requires from its `preconditions`. Only entries that start with `skill:git+` are
37
+ * references; everything else, other `skill:` text included, stays an ordinary precondition. A reference that
38
+ * cannot be honoured in full is an error, not a shorter list: installing some of what a Gene needs would hand the
39
+ * agent a broken strategy.
40
+ */
41
+ export declare function requiredSkillsOf(gene: Record<string, unknown>): Result<RequiredSkillRef[]>;
42
+ /** The `preconditions` entry that pins a skill directory with this content. */
43
+ export declare function formatRequiredSkill(ref: Pick<RequiredSkillRef, 'repo' | 'commit' | 'path' | 'sha256'>): string;
44
+ /**
45
+ * Content digest of a skill directory: SHA-256 over one `<sha256 of the file> <path>\n` line per file, sorted by
46
+ * path. It is the output of `sha256sum` over the sorted files, so an author can reproduce it without this tool.
47
+ */
48
+ export declare function digestOfSkillFiles(files: readonly SkillFile[]): string;
49
+ /** Decide from the tree listing alone, before any file content is read, whether this directory may be installed. */
50
+ export declare function checkSkillTree(entries: readonly SkillTreeEntry[]): Result<true>;
@@ -0,0 +1,123 @@
1
+ import { createHash } from 'node:crypto';
2
+ const GIT_PREFIX = 'skill:git+';
3
+ const MAX_REQUIRED_SKILLS = 8;
4
+ const MAX_FILES = 256;
5
+ const MAX_FILE_BYTES = 5 * 1024 * 1024;
6
+ const MAX_TOTAL_BYTES = 20 * 1024 * 1024;
7
+ const MAX_DEPTH = 8;
8
+ const COMMIT = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
9
+ const SHA256 = /^[0-9a-f]{64}$/;
10
+ const SEGMENT = /^[A-Za-z0-9._-]{1,100}$/;
11
+ // Windows opens these as devices, extension or not (CON, NUL.txt, COM1.md), so they never name a plain file.
12
+ const WINDOWS_DEVICE = /^(?:con|prn|aux|nul|com\d|lpt\d)(?:\.|$)/i;
13
+ const REGULAR_FILE_MODES = new Set(['100644', '100755']);
14
+ /**
15
+ * Read the skills a Gene requires from its `preconditions`. Only entries that start with `skill:git+` are
16
+ * references; everything else, other `skill:` text included, stays an ordinary precondition. A reference that
17
+ * cannot be honoured in full is an error, not a shorter list: installing some of what a Gene needs would hand the
18
+ * agent a broken strategy.
19
+ */
20
+ export function requiredSkillsOf(gene) {
21
+ const preconditions = Array.isArray(gene['preconditions']) ? gene['preconditions'] : [];
22
+ const declared = preconditions.filter((entry) => typeof entry === 'string' && entry.startsWith(GIT_PREFIX));
23
+ if (declared.length > MAX_REQUIRED_SKILLS)
24
+ return { ok: false, message: `a Gene may require at most ${MAX_REQUIRED_SKILLS} skills` };
25
+ const refs = [];
26
+ for (const entry of declared) {
27
+ const ref = parseRequiredSkill(entry);
28
+ if (!ref.ok)
29
+ return ref;
30
+ if (refs.some((known) => known.name === ref.value.name)) {
31
+ return { ok: false, message: `two required skills would install to skills/${ref.value.name}` };
32
+ }
33
+ refs.push(ref.value);
34
+ }
35
+ return { ok: true, value: refs };
36
+ }
37
+ function parseRequiredSkill(entry) {
38
+ const malformed = (why) => ({ ok: false, message: `required skill reference is not valid (${why})` });
39
+ const [location = '', fragment = '', ...extra] = entry.slice(GIT_PREFIX.length).split('#');
40
+ const at = location.lastIndexOf('@');
41
+ if (extra.length > 0 || at < 0)
42
+ return malformed('expected <repository>@<commit>#sha256=<digest>');
43
+ const repo = httpsRepository(location.slice(0, at));
44
+ const commit = location.slice(at + 1);
45
+ const pin = pinOf(fragment);
46
+ if (!repo)
47
+ return malformed('the repository must be a plain https:// URL without credentials or query');
48
+ if (!COMMIT.test(commit))
49
+ return malformed('the commit must be a full lowercase hex commit id');
50
+ if (!pin)
51
+ return malformed('expected #sha256=<64 lowercase hex>, optionally &path=<plain relative directory>');
52
+ const { sha256, path } = pin;
53
+ const name = installName(path || new URL(repo).pathname);
54
+ if (!name)
55
+ return malformed('no usable directory name');
56
+ return { ok: true, value: { name, repo, commit, path, sha256 } };
57
+ }
58
+ function pinOf(fragment) {
59
+ const params = new URLSearchParams(fragment);
60
+ const sha256 = params.get('sha256') ?? '';
61
+ const path = params.get('path') ?? '';
62
+ const known = [...params.keys()].every((key) => key === 'sha256' || key === 'path');
63
+ return known && SHA256.test(sha256) && (path === '' || isSafeRelativePath(path)) ? { sha256, path } : null;
64
+ }
65
+ function httpsRepository(raw) {
66
+ let url;
67
+ try {
68
+ url = new URL(raw);
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ const plain = url.protocol === 'https:' && !url.username && !url.password && !url.search && !url.hash && url.pathname.length > 1;
74
+ return plain && url.href === raw ? raw : null;
75
+ }
76
+ function installName(source) {
77
+ const last = source.split('/').filter(Boolean).pop() ?? '';
78
+ return last.replace(/\.git$/i, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80);
79
+ }
80
+ /** The `preconditions` entry that pins a skill directory with this content. */
81
+ export function formatRequiredSkill(ref) {
82
+ const params = new URLSearchParams({ sha256: ref.sha256, ...(ref.path ? { path: ref.path } : {}) });
83
+ return `${GIT_PREFIX}${ref.repo}@${ref.commit}#${params.toString().replace(/%2F/g, '/')}`;
84
+ }
85
+ /**
86
+ * Content digest of a skill directory: SHA-256 over one `<sha256 of the file> <path>\n` line per file, sorted by
87
+ * path. It is the output of `sha256sum` over the sorted files, so an author can reproduce it without this tool.
88
+ */
89
+ export function digestOfSkillFiles(files) {
90
+ const lines = [...files]
91
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
92
+ .map((file) => `${createHash('sha256').update(file.content).digest('hex')} ${file.path}\n`);
93
+ return createHash('sha256').update(lines.join('')).digest('hex');
94
+ }
95
+ /** Decide from the tree listing alone, before any file content is read, whether this directory may be installed. */
96
+ export function checkSkillTree(entries) {
97
+ if (!entries.some((entry) => entry.path === 'SKILL.md'))
98
+ return { ok: false, message: 'the directory has no SKILL.md' };
99
+ if (entries.length > MAX_FILES)
100
+ return { ok: false, message: `it has more than ${MAX_FILES} files` };
101
+ const seen = new Set();
102
+ let total = 0;
103
+ for (const entry of entries) {
104
+ if (entry.type !== 'blob' || !REGULAR_FILE_MODES.has(entry.mode)) {
105
+ return { ok: false, message: `${entry.path} is a symlink or submodule, not a regular file` };
106
+ }
107
+ if (!isSafeRelativePath(entry.path) || seen.has(entry.path.toLowerCase())) {
108
+ return { ok: false, message: `${JSON.stringify(entry.path)} is not a plain, unique relative path` };
109
+ }
110
+ seen.add(entry.path.toLowerCase());
111
+ total += entry.size;
112
+ if (entry.size > MAX_FILE_BYTES || total > MAX_TOTAL_BYTES) {
113
+ return { ok: false, message: `it is larger than ${MAX_FILE_BYTES} bytes per file or ${MAX_TOTAL_BYTES} bytes in total` };
114
+ }
115
+ }
116
+ return { ok: true, value: true };
117
+ }
118
+ function isSafeRelativePath(path) {
119
+ const segments = path.split('/');
120
+ return segments.length <= MAX_DEPTH
121
+ && segments.every((segment) => SEGMENT.test(segment) && !/^\.+$/.test(segment) && segment.toLowerCase() !== '.git' && !segment.endsWith('.')
122
+ && !WINDOWS_DEVICE.test(segment));
123
+ }
@@ -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,6 @@
1
1
  import { assetstore, type hub as hubNs } from '@evomap/evolver-core';
2
2
  import type { ConnectPublicOptions, PublicHubCapability } from '@evomap/evolver-adapter-public';
3
+ import { type RequiredSkillRef, type Result, type SkillFile } from './requiredSkills.js';
3
4
  export interface SkillFetchHub {
4
5
  search(query: assetstore.SearchQuery): Promise<assetstore.AssetRecord[]>;
5
6
  fetch(query: assetstore.SearchQuery): Promise<assetstore.AssetRecord[]>;
@@ -15,5 +16,7 @@ export interface SkillFetchDeps {
15
16
  hub: PublicHubCapability;
16
17
  auth: hubNs.AuthProvider;
17
18
  };
19
+ /** Fetches a required skill's files from its git repository; the network boundary of an install. */
20
+ fetchSkillFiles?: (ref: RequiredSkillRef) => Result<SkillFile[]>;
18
21
  }
19
22
  export declare function runSkillCommand(argv: readonly string[], deps?: SkillFetchDeps): Promise<number>;
@@ -1,9 +1,12 @@
1
- import { join } from 'node:path';
1
+ import { lstatSync, readdirSync } from 'node:fs';
2
+ import { join, sep } from 'node:path';
2
3
  import { assetstore, wire } from '@evomap/evolver-core';
3
- import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled, } from '@evomap/evolver-adapter-public';
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';
7
+ import { fetchSkillFiles } from './gitSkillSource.js';
6
8
  import { createRecipeHubFromEnv } from './recipe.js';
9
+ import { digestOfSkillFiles, requiredSkillsOf } from './requiredSkills.js';
7
10
  import { geneToSkillMd } from './skillDistill.js';
8
11
  const GROUP = 'skill.fetch';
9
12
  const DEFAULT_LIMIT = 5;
@@ -14,27 +17,6 @@ const USAGE = [
14
17
  ' evolver skill fetch --signals <s1,s2> [--limit N] [--select <asset_id_or_gene_id>] [--out <dir>] [--write] [--force] [--json]',
15
18
  ' evolver skill fetch --query <text> [--limit N] [--select <asset_id_or_gene_id>] [--out <dir>] [--write] [--force] [--json]',
16
19
  ].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
20
  export async function runSkillCommand(argv, deps = {}) {
39
21
  const sub = argv[0];
40
22
  if (sub === 'fetch')
@@ -66,7 +48,7 @@ async function runSkillFetchCommand(argv, deps = {}) {
66
48
  return 0;
67
49
  }
68
50
  const hub = deps.hub ?? createSkillFetchHubFromEnv(deps, env);
69
- const run = await buildSkillFetchResult(hub, opts, cwd);
51
+ const run = await buildSkillFetchResult(hub, opts, cwd, deps.fetchSkillFiles ?? fetchSkillFiles);
70
52
  if (!run.ok)
71
53
  return emitFailure(run.reason, run.message, opts.json, io);
72
54
  emitSuccess(run.value, opts.json, io);
@@ -128,7 +110,7 @@ function parseSkillFetchArgs(argv, cwd) {
128
110
  },
129
111
  };
130
112
  }
131
- async function buildSkillFetchResult(hub, opts, cwd) {
113
+ async function buildSkillFetchResult(hub, opts, cwd, fetchFiles) {
132
114
  const direct = opts.source.kind === 'asset' ? await fetchGeneById(hub, opts.source.id) : null;
133
115
  if (direct && !direct.ok)
134
116
  return direct;
@@ -158,7 +140,7 @@ async function buildSkillFetchResult(hub, opts, cwd) {
158
140
  if (selected.asset.asset_id !== previewed.assetId) {
159
141
  return { ok: false, reason: 'integrity_error', message: 'selected Gene asset_id changed after preview' };
160
142
  }
161
- const written = writeSkill(selected.asset, cwd, opts.outDir, opts.force);
143
+ const written = writeSkill(selected.asset, cwd, opts.outDir, opts.force, fetchFiles);
162
144
  if (!written.ok)
163
145
  return written;
164
146
  return { ok: true, value: { mode: 'write', candidates: [candidateFromGene(selected.asset, opts.outDir)], written: written.value } };
@@ -200,7 +182,7 @@ async function fetchGeneById(hub, id) {
200
182
  function normalizeRemoteGene(asset, requestedId) {
201
183
  if (asset.type !== 'Gene')
202
184
  return { ok: false, reason: 'unsupported', message: `skill fetch only supports Gene assets, got ${asset.type}` };
203
- const cleaned = stripHubMetadata(asset);
185
+ const cleaned = stripHubDeliveryMetadataForIntegrity(asset);
204
186
  const claimed = stringField(cleaned, 'asset_id');
205
187
  if (!claimed)
206
188
  return { ok: false, reason: 'integrity_error', message: 'remote Gene is missing asset_id' };
@@ -213,6 +195,9 @@ function normalizeRemoteGene(asset, requestedId) {
213
195
  if (!isContentAssetId(requestedId) && stringField(cleaned, 'id') !== requestedId)
214
196
  return { ok: false, reason: 'integrity_error', message: 'remote Gene id does not match requested id' };
215
197
  }
198
+ const required = requiredSkillsOf(cleaned);
199
+ if (!required.ok)
200
+ return { ok: false, reason: 'unsupported', message: `Gene ${required.message}` };
216
201
  return { ok: true, asset: cleaned };
217
202
  }
218
203
  function candidateFromGene(gene, outDir) {
@@ -230,22 +215,95 @@ function candidateFromGene(gene, outDir) {
230
215
  candidate.summary = summary;
231
216
  if (outDir)
232
217
  candidate.target = relativeSkillPath(name);
218
+ const required = requiredSkillsOf(gene);
219
+ if (required.ok && required.value.length > 0)
220
+ candidate.requiredSkills = required.value;
233
221
  return candidate;
234
222
  }
235
- function writeSkill(gene, cwd, outDir, force) {
223
+ function writeSkill(gene, cwd, outDir, force, fetchFiles) {
236
224
  const name = skillNameForGene(gene);
237
225
  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' };
226
+ const required = planRequiredSkills(gene, name, fetchFiles);
227
+ if (!required.ok)
228
+ return required;
229
+ const skillMd = geneToSkillMd(gene, {
230
+ name,
231
+ requiredSkills: required.value.map(({ skill }) => ({ name: skill.name, path: `../${skill.name}/SKILL.md` })),
232
+ });
233
+ // The Gene's own SKILL.md goes last: its presence then means everything it points at is already on disk.
234
+ const planned = [...required.value.flatMap((plan) => plan.planned), { target, content: skillMd }];
235
+ if (required.value.length > 0) {
236
+ const blocked = installBlocker(cwd, outDir, planned, required.value.map((plan) => plan.skill.name), force);
237
+ if (blocked)
238
+ return blocked;
239
+ }
240
+ for (const file of planned) {
241
+ const write = writeFileInsideRoot(cwd, join(outDir, ...file.target.split('/')), file.content, force);
242
+ if (!write.ok && write.reason === 'exists')
243
+ return { ok: false, reason: 'conflict', message: `SKILL.md already exists for skill ${name}; use --force to overwrite` };
244
+ if (!write.ok)
245
+ return { ok: false, reason: 'invalid_arg', message: 'skill target path must not pass through a symlink, junction, hard link, or non-directory' };
246
+ }
243
247
  const written = { target, assetId: gene.asset_id, name };
244
248
  const geneId = stringField(gene, 'id');
245
249
  if (geneId)
246
250
  written.geneId = geneId;
251
+ if (required.value.length > 0)
252
+ written.requiredSkills = required.value.map((plan) => plan.skill);
247
253
  return { ok: true, value: written };
248
254
  }
255
+ /**
256
+ * Decide before the first write whether the whole install can land: every target writable, and each skill
257
+ * directory free of files the pinned skill does not have, so what is on disk afterwards is exactly the pinned
258
+ * content. Leftovers are refused, not deleted: they may be the user's.
259
+ */
260
+ function installBlocker(cwd, outDir, planned, skillNames, force) {
261
+ const pathOf = (target) => join(outDir, ...target.split('/'));
262
+ for (const file of planned) {
263
+ const check = checkWriteInsideRoot(cwd, pathOf(file.target), force);
264
+ if (!check.ok && check.reason === 'exists')
265
+ return { ok: false, reason: 'conflict', message: `${file.target} already exists; use --force to overwrite. Nothing was written` };
266
+ if (!check.ok)
267
+ 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' };
268
+ }
269
+ const expected = new Set(planned.map((file) => file.target));
270
+ for (const name of skillNames) {
271
+ const stray = filesUnder(join(cwd, pathOf(`skills/${name}`)), `skills/${name}`).find((target) => !expected.has(target));
272
+ if (stray)
273
+ return { ok: false, reason: 'conflict', message: `${stray} is not part of the pinned skill; remove skills/${name} and retry. Nothing was written` };
274
+ }
275
+ return null;
276
+ }
277
+ function filesUnder(dir, target) {
278
+ let stat;
279
+ try {
280
+ stat = lstatSync(dir);
281
+ }
282
+ catch {
283
+ return [];
284
+ }
285
+ if (!stat.isDirectory())
286
+ return [target];
287
+ return readdirSync(dir).flatMap((entry) => filesUnder(`${dir}${sep}${entry}`, `${target}/${entry}`));
288
+ }
289
+ /** Fetch every skill the Gene requires and check it against the Gene's pin before a single file is written. */
290
+ function planRequiredSkills(gene, geneSkillName, fetchFiles) {
291
+ const declared = requiredSkillsOf(gene);
292
+ const plans = [];
293
+ for (const ref of declared.ok ? declared.value : []) {
294
+ const refuse = (why) => ({ ok: false, reason: 'required_skill', message: `required skill ${ref.name} cannot be installed: ${why}. Nothing was written` });
295
+ if (ref.name === safeSkillName(geneSkillName))
296
+ return refuse('its directory name collides with the skill rendered from this Gene');
297
+ const files = fetchFiles(ref);
298
+ if (!files.ok)
299
+ return refuse(files.message);
300
+ if (digestOfSkillFiles(files.value) !== ref.sha256)
301
+ return refuse('its content does not match the sha256 the Gene pins');
302
+ const planned = files.value.map((file) => ({ target: `skills/${ref.name}/${file.path}`, content: file.content }));
303
+ plans.push({ skill: { ...ref, target: `skills/${ref.name}/SKILL.md`, files: planned.map((file) => file.target) }, planned });
304
+ }
305
+ return { ok: true, value: plans };
306
+ }
249
307
  function createSkillFetchHubFromEnv(deps, env = deps.env ?? process.env) {
250
308
  return createRecipeHubFromEnv(env, deps.connectHub ?? connectPublicHub);
251
309
  }
@@ -263,10 +321,14 @@ function emitSuccess(value, json, io) {
263
321
  const gene = c.geneId ? ` gene=${c.geneId}` : '';
264
322
  const signals = c.signals.length > 0 ? ` signals=${c.signals.join(',')}` : '';
265
323
  const target = c.target ? ` target=${c.target}` : '';
266
- io.stdout(` ${c.assetId}${gene} name=${c.name}${signals}${target}`);
324
+ const requires = c.requiredSkills ? ` requires=${c.requiredSkills.map((skill) => skill.name).join(',')}` : '';
325
+ io.stdout(` ${c.assetId}${gene} name=${c.name}${signals}${target}${requires}`);
267
326
  if (c.summary)
268
327
  io.stdout(` ${c.summary}`);
269
328
  }
329
+ for (const skill of value.written?.requiredSkills ?? []) {
330
+ io.stdout(`skill fetch: installed required skill ${skill.name} (${skill.files.length} file(s)) from ${skill.repo}@${skill.commit.slice(0, 12)}`);
331
+ }
270
332
  if (value.written)
271
333
  io.stdout(`skill fetch: wrote ${value.written.target}`);
272
334
  }
@@ -339,13 +401,6 @@ function flagValue(args, flag) {
339
401
  function splitList(value) {
340
402
  return value.split(',').map((item) => item.trim()).filter(Boolean);
341
403
  }
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
404
  function skillNameForGene(gene) {
350
405
  const signals = arrayOfStrings(gene['signals_match']).slice(0, 4).join('-');
351
406
  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.54",
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.54",
31
+ "@evomap/evolver-adapter-public": "2.0.54",
32
+ "@evomap/evolver-mcp": "2.0.54",
33
+ "@evomap/evolver-proxy": "2.0.54",
34
+ "@evomap/evolver-runtime-adapters": "2.0.54",
35
+ "@evomap/evolver-webui": "2.0.54"
36
36
  },
37
37
  "repository": {
38
38
  "type": "git",