@evomap/evolver-cli 2.0.52 → 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
+ }
package/dist/lifecycle.js CHANGED
@@ -3766,6 +3766,18 @@ function recoverBootstrapTransaction(stateDir, run, uid, now, deadlineMs, assert
3766
3766
  return { status: 'none' };
3767
3767
  }
3768
3768
  const marker = readBootstrapMarker(stateDir);
3769
+ if (marker && journal.stage === 'rollback_pending') {
3770
+ assertBootstrapMarkerMatchesJournal(marker, journal);
3771
+ rollbackBootstrapTransaction(stateDir, journal, run, uid, now, deadlineMs, true, true, assertOwner);
3772
+ assertOwner();
3773
+ restoreBootstrapCanonicalQuarantine(stateDir, journal, {
3774
+ beforeMove: () => assertOwner(),
3775
+ afterMove: () => assertOwner(),
3776
+ });
3777
+ assertOwner();
3778
+ removeBootstrapJournal(stateDir);
3779
+ return { status: 'none' };
3780
+ }
3769
3781
  if (marker) {
3770
3782
  assertBootstrapMarkerMatchesJournal(marker, journal);
3771
3783
  assertOwner();
package/dist/plugin.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type PluginRuntime } from './pluginRuntime.js';
2
- export declare const PLUGIN_USAGE = "Usage: evolver plugin list [--json]\n evolver plugin install [--host <host>] [--scope user|project] [--root <dir>]\n [--profile <dsh-profile>] [--trust] [--dry-run] [--json]\n\nHosts: claude-code, codex, grok, qoder, antigravity, opencode, dsh, zcode,\n kimi, stepcode, minimax, cursor, workbuddy, mcp-generic\nDefault scope: user. dsh default profile: dsh-tui.\n--trust says you trust the plugin's hooks; only hosts that require it (grok) accept it.\nWith no host, only a single discovered native host is selected; otherwise choose --host.\nCursor, WorkBuddy and generic MCP return manual_required without writing client config.\nKimi Code and Step Code install on Windows only; ZCode on Windows and macOS.\nDry-run performs no download, host command or config write and proves no installed state.\nInstallation uses EvoMap/evolver-agent-plugin and does not replace setup-hooks.\nExit codes: 0 verified install/already-installed/list/preview; 2 action required\n(including trust_required and profile_store_mismatch); 1 conflict or failure.\n";
2
+ export declare const PLUGIN_USAGE = "Usage: evolver plugin list [--json]\n evolver plugin install [--host <host>] [--scope user|project] [--root <dir>]\n [--profile <dsh-profile>] [--trust] [--dry-run] [--json]\n\nHosts: claude-code, codex, grok, qoder, antigravity, opencode, dsh, zcode,\n kimi, stepcode, minimax, cursor, workbuddy, mcp-generic\nDefault scope: user. dsh default profile: dsh-tui.\n--trust says you trust the plugin's hooks; only hosts that require it (grok) accept it.\nWith no host, only a single discovered native host is selected; otherwise choose --host.\nCursor, WorkBuddy and generic MCP return manual_required without writing client config.\nKimi Code, Step Code and ZCode install on Windows and macOS.\nZCode installs evolver-plugin@evomap from the evolver-agent-plugin ZCode marketplace\nURL, after uninstalling an evolver-plugin@evolver-zcode-local install (data kept).\nDry-run performs no download, host command or config write and proves no installed state.\nInstallation uses EvoMap/evolver-agent-plugin and does not replace setup-hooks.\nExit codes: 0 verified install/already-installed/list/preview; 2 action required\n(including trust_required and profile_store_mismatch); 1 conflict or failure.\n";
3
3
  export interface PluginCommandDeps {
4
4
  runtime?: PluginRuntime;
5
5
  stdout?: (text: string) => void;
package/dist/plugin.js CHANGED
@@ -14,7 +14,9 @@ Default scope: user. dsh default profile: dsh-tui.
14
14
  --trust says you trust the plugin's hooks; only hosts that require it (grok) accept it.
15
15
  With no host, only a single discovered native host is selected; otherwise choose --host.
16
16
  Cursor, WorkBuddy and generic MCP return manual_required without writing client config.
17
- Kimi Code and Step Code install on Windows only; ZCode on Windows and macOS.
17
+ Kimi Code, Step Code and ZCode install on Windows and macOS.
18
+ ZCode installs evolver-plugin@evomap from the evolver-agent-plugin ZCode marketplace
19
+ URL, after uninstalling an evolver-plugin@evolver-zcode-local install (data kept).
18
20
  Dry-run performs no download, host command or config write and proves no installed state.
19
21
  Installation uses EvoMap/evolver-agent-plugin and does not replace setup-hooks.
20
22
  Exit codes: 0 verified install/already-installed/list/preview; 2 action required
@@ -3,6 +3,7 @@ export declare const AGENT_PLUGIN_GIT_URL = "https://github.com/EvoMap/evolver-a
3
3
  export declare const AGENT_PLUGIN_NAME = "evolver-plugin";
4
4
  export declare const AGENT_PLUGIN_RELEASE = "release";
5
5
  export declare const DSH_PLUGIN_SOURCE = "github:EvoMap/evolver-agent-plugin#release&path:dist/dsh";
6
+ export declare const ZCODE_LOCAL_MARKETPLACE = "evolver-zcode-local";
6
7
  export declare function agentPluginRepositoryMatches(value: unknown): boolean;
7
8
  export type PluginScope = 'user' | 'project';
8
9
  type PluginHostId = 'claude-code' | 'codex' | 'grok' | 'qoder' | 'antigravity' | 'opencode' | 'dsh' | 'zcode' | 'kimi' | 'stepcode' | 'minimax' | 'cursor' | 'workbuddy' | 'mcp-generic';
@@ -18,6 +19,8 @@ export interface PluginHost {
18
19
  platforms?: readonly NodeJS.Platform[];
19
20
  management?: 'plugin' | 'plugins';
20
21
  marketplace?: string;
22
+ /** What `marketplace add` registers when it is not the plugin repository itself. */
23
+ marketplaceSource?: string;
21
24
  manifest?: string;
22
25
  packageName?: string;
23
26
  /** Files an installed (and packed) plugin must contain besides its manifest. */
@@ -4,6 +4,9 @@ export const AGENT_PLUGIN_GIT_URL = `https://github.com/${AGENT_PLUGIN_REPOSITOR
4
4
  export const AGENT_PLUGIN_NAME = 'evolver-plugin';
5
5
  export const AGENT_PLUGIN_RELEASE = 'release';
6
6
  export const DSH_PLUGIN_SOURCE = `github:${AGENT_PLUGIN_REPOSITORY}#${AGENT_PLUGIN_RELEASE}&path:dist/dsh`;
7
+ /** ZCode resolves a repository marketplace from `.claude-plugin/marketplace.json` first, so it gets its own manifest by URL. */
8
+ const ZCODE_MARKETPLACE_URL = `https://raw.githubusercontent.com/${AGENT_PLUGIN_REPOSITORY}/main/.zcode-plugin/marketplace.json`;
9
+ export const ZCODE_LOCAL_MARKETPLACE = 'evolver-zcode-local';
7
10
  export function agentPluginRepositoryMatches(value) {
8
11
  if (typeof value !== 'string')
9
12
  return false;
@@ -51,25 +54,27 @@ export const PLUGIN_HOSTS = [
51
54
  instructions: ['Restart dsh. Installation applies only to the selected profile; repeat for other profiles. DSH Desktop requires its own bundled CLI/profile.'],
52
55
  },
53
56
  {
54
- id: 'zcode', label: 'ZCode', command: 'zcode', kind: 'bundle', management: 'plugins', marketplace: 'evolver-zcode-local',
57
+ id: 'zcode', label: 'ZCode', command: 'zcode', kind: 'marketplace', management: 'plugins', marketplace: 'evomap', marketplaceSource: ZCODE_MARKETPLACE_URL,
55
58
  scopes: ['user'], platforms: ['win32', 'darwin'], manifest: '.zcode-plugin/plugin.json', entries: ['hooks/hooks.json', 'bin/hook.mjs'], legacyNames: [],
56
59
  instructions: [
57
60
  'Start a new ZCode session. ZCode CLI and Desktop share this installation; plugins and hooks must be enabled in ZCode.',
58
61
  'Evolver runs the CLI shipped with ZCode Desktop, or the standalone zcode.cjs named by ZCODE_CLI_PATH.',
62
+ `The evomap marketplace is ${ZCODE_MARKETPLACE_URL}; plugins update evolver-plugin@evomap follows each release.`,
63
+ `An evolver-plugin@${ZCODE_LOCAL_MARKETPLACE} install is uninstalled first, keeping its data, so hooks do not run twice; its marketplace is removed only when it points into Evolver's release cache.`,
59
64
  ],
60
65
  },
61
66
  {
62
67
  id: 'kimi', label: 'Kimi Code', command: 'kimi', kind: 'script', installer: 'scripts/install-kimi.mjs',
63
- scopes: ['user'], platforms: ['win32'], manifest: 'kimi.plugin.json', entries: ['bin/hook.mjs'], legacyNames: [],
68
+ scopes: ['user'], platforms: ['win32', 'darwin'], manifest: 'kimi.plugin.json', entries: ['bin/hook.mjs'], legacyNames: [],
64
69
  instructions: [
65
70
  'Close Kimi Code before installing or updating, then start a new CLI or Desktop session.',
66
71
  'KIMI_CODE_HOME selects the profile root; start Kimi with the same value.',
67
72
  ],
68
73
  },
69
74
  {
70
- id: 'stepcode', label: 'Step Code', command: 'step', kind: 'bundle', scopes: ['user'], platforms: ['win32'],
75
+ id: 'stepcode', label: 'Step Code', command: 'step', kind: 'bundle', scopes: ['user'], platforms: ['win32', 'darwin'],
71
76
  manifest: 'package.json', packageName: '@evomap/stepcode-evolver', entries: ['plugin.mjs'], legacyNames: [],
72
- instructions: ['Start a new Step Code session. The adapter is a Windows draft for Step Code CLI 0.1.7; STEP_CODING_AGENT_DIR selects the profile.'],
77
+ instructions: ['Start a new Step Code session. The adapter is verified with Step Code CLI 0.1.7 on Windows and macOS; STEP_CODING_AGENT_DIR selects the profile.'],
73
78
  },
74
79
  {
75
80
  id: 'minimax', label: 'MiniMax Code', command: 'mcode', kind: 'script', installer: 'scripts/install-minimax.mjs',
@@ -118,10 +123,11 @@ export function pluginHostNamed(name) {
118
123
  function marketplaceInstallSteps({ host, scope, trust }, step) {
119
124
  const management = host.management;
120
125
  const selector = host.id === 'grok' ? AGENT_PLUGIN_NAME : `${AGENT_PLUGIN_NAME}@${host.marketplace}`;
126
+ const scoped = host.id === 'claude-code' || host.id === 'zcode';
121
127
  const install = host.id === 'codex'
122
128
  ? [management, 'add', selector, '--json']
123
- : [management, 'install', selector, ...(host.id === 'claude-code' ? ['--scope', scope, '--json'] : []), ...(host.requiresTrust && trust ? ['--trust'] : [])];
124
- return [step('marketplace', [management, 'marketplace', 'add', AGENT_PLUGIN_REPOSITORY]), step('install', install)];
129
+ : [management, 'install', selector, ...(scoped ? ['--scope', scope, '--json'] : []), ...(host.requiresTrust && trust ? ['--trust'] : [])];
130
+ return [step('marketplace', [management, 'marketplace', 'add', host.marketplaceSource ?? AGENT_PLUGIN_REPOSITORY]), step('install', install)];
125
131
  }
126
132
  function scriptInstallSteps(host, bundle, step) {
127
133
  const installer = { name: 'install', command: 'node', args: [join(dirname(bundle), host.installer), 'install'] };
@@ -135,12 +141,6 @@ export function pluginInstallSteps(options, bundle = '<release-checkout>/dist')
135
141
  return marketplaceInstallSteps(options, step);
136
142
  if (host.kind === 'script')
137
143
  return scriptInstallSteps(host, bundle, step);
138
- if (host.id === 'zcode') {
139
- return [
140
- step('marketplace', ['plugins', 'marketplace', 'add', join(bundle, 'zcode'), '--json']),
141
- step('install', ['plugins', 'install', `${AGENT_PLUGIN_NAME}@${host.marketplace}`, '--scope', scope, '--json']),
142
- ];
143
- }
144
144
  if (host.id === 'antigravity')
145
145
  return [step('install', ['plugin', 'install', `${bundle}/antigravity`])];
146
146
  if (host.id === 'opencode')
@@ -169,7 +169,7 @@ export function pluginRollbackInstructions(options, bundle = '<release-checkout>
169
169
  if (host.id === 'opencode')
170
170
  return [`Remove only this plugin's ${bundle}/opencode/server.mjs and tui.mjs entries from opencode.json and tui.json; preserve neighboring configuration.`];
171
171
  if (host.id === 'zcode')
172
- return [`${cli} plugins uninstall ${AGENT_PLUGIN_NAME}@${host.marketplace} --scope ${scope}`];
172
+ return [`${cli} plugins uninstall ${AGENT_PLUGIN_NAME}@${host.marketplace} --scope ${scope} --keep-data`, `${cli} plugins marketplace remove ${host.marketplace}`];
173
173
  if (host.id === 'kimi')
174
174
  return [`node ${join(dirname(bundle), host.installer)} remove`];
175
175
  if (host.id === 'stepcode')
@@ -1,4 +1,5 @@
1
1
  import { type PluginInstallOptions, type PluginHost } from './pluginHosts.js';
2
+ import { type ZcodeLocalInstall } from './pluginZcodeMigration.js';
2
3
  import { type PluginRuntime } from './pluginRuntime.js';
3
4
  export interface InstalledAgentPlugin {
4
5
  id: string;
@@ -16,6 +17,7 @@ export interface PluginInspection {
16
17
  conflicts: string[];
17
18
  /** Native commands the user can run to remove a conflicting standalone plugin; never run automatically. */
18
19
  migrations: string[];
20
+ zcodeLocal?: ZcodeLocalInstall;
19
21
  }
20
22
  export declare function installedPluginsFromJson(value: unknown, host: PluginHost): InstalledAgentPlugin[];
21
23
  export declare function verifyPluginManifest(runtime: PluginRuntime, options: PluginInstallOptions, plugin: InstalledAgentPlugin, installAnswer?: unknown): string;
@@ -3,8 +3,8 @@ import { existsSync } from 'node:fs';
3
3
  import { dirname, join, resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { agentPluginRepositoryMatches, AGENT_PLUGIN_NAME, AGENT_PLUGIN_REPOSITORY, standalonePluginRemoval } from './pluginHosts.js';
6
- import { isManagedPackedBundle } from './pluginBundle.js';
7
6
  import { inspectScriptPlugin, inspectStepCodePlugin } from './pluginLocalInspection.js';
7
+ import { zcodeLocalInstall } from './pluginZcodeMigration.js';
8
8
  import { checkedPluginCommand, objectOf, pluginHome, pluginJson, pluginVersionAtLeast, PluginInstallError, readPluginJson, readPluginText } from './pluginRuntime.js';
9
9
  function listRecords(value, key, label) {
10
10
  const list = Array.isArray(value) ? value : objectOf(value)?.[key];
@@ -35,13 +35,10 @@ function repositoryOf(record) {
35
35
  ?? objectOf(record['source'])?.['url'] ?? (typeof record['source'] === 'string' ? record['source'] : undefined);
36
36
  }
37
37
  async function marketplaceMatches(runtime, host, record) {
38
+ if (host.marketplaceSource)
39
+ return objectOf(record['source'])?.['url'] === host.marketplaceSource;
38
40
  if (agentPluginRepositoryMatches(repositoryOf(record)))
39
41
  return true;
40
- const source = objectOf(record['source']);
41
- if (source?.['source'] === 'directory') {
42
- const folder = stringOf(source['path']);
43
- return folder !== undefined && isManagedPackedBundle(runtime, host, folder);
44
- }
45
42
  const root = stringOf(record['root']) ?? stringOf(record['installLocation']);
46
43
  if (!root)
47
44
  return false;
@@ -94,14 +91,15 @@ async function inspectMarketplacePlugin(runtime, options) {
94
91
  const market = markets.find(record => record['name'] === host.marketplace);
95
92
  const conflicts = oldHookConflicts(runtime, options);
96
93
  const migrations = [];
94
+ const zcodeLocal = host.id === 'zcode' ? zcodeLocalInstall(runtime, host, plugins.map(plugin => plugin.id), markets) : undefined;
97
95
  if (market && !await marketplaceMatches(runtime, host, market))
98
- conflicts.push(`Marketplace ${host.marketplace} belongs to another source. Review its plugins before replacing it with ${AGENT_PLUGIN_REPOSITORY}.`);
96
+ conflicts.push(`Marketplace ${host.marketplace} belongs to another source. Review its plugins before replacing it with ${host.marketplaceSource ?? AGENT_PLUGIN_REPOSITORY}.`);
99
97
  for (const plugin of plugins) {
100
98
  if (host.legacyNames.includes(plugin.name) && plugin.enabled) {
101
99
  conflicts.push(`The standalone ${plugin.name} plugin is enabled. Disable/remove it using ${host.label}, keeping its data, before installing ${AGENT_PLUGIN_NAME}.`);
102
100
  migrations.push(standalonePluginRemoval(options, plugin));
103
101
  }
104
- if (plugin.name === AGENT_PLUGIN_NAME && plugin.id !== `${AGENT_PLUGIN_NAME}@${host.marketplace}` && !(host.id === 'grok' && plugin.id === AGENT_PLUGIN_NAME))
102
+ if (plugin.name === AGENT_PLUGIN_NAME && plugin.id !== `${AGENT_PLUGIN_NAME}@${host.marketplace}` && plugin.id !== zcodeLocal?.uninstall && !(host.id === 'grok' && plugin.id === AGENT_PLUGIN_NAME))
105
103
  conflicts.push('An Evolver plugin from another marketplace is registered; review that installation before continuing.');
106
104
  }
107
105
  const installed = plugins.find(plugin => (plugin.id === `${AGENT_PLUGIN_NAME}@${host.marketplace}` || (host.id === 'grok' && plugin.id === AGENT_PLUGIN_NAME)) && (host.id !== 'claude-code' || plugin.scope === scope));
@@ -111,7 +109,7 @@ async function inspectMarketplacePlugin(runtime, options) {
111
109
  conflicts.push('The plugin is installed but disabled. Enable it explicitly in the host rather than installing another copy.');
112
110
  if (installed && host.id === 'codex' && !agentPluginRepositoryMatches(repositoryOf(installed.raw)))
113
111
  conflicts.push('The installed plugin source does not match the unified Evolver plugin repository.');
114
- return { installed, marketplacePresent: Boolean(market), conflicts, migrations };
112
+ return { installed, marketplacePresent: Boolean(market), conflicts, migrations, zcodeLocal };
115
113
  }
116
114
  export function verifyPluginManifest(runtime, options, plugin, installAnswer) {
117
115
  const { host } = options;
@@ -1,5 +1,6 @@
1
1
  import { type PluginCommandStep, type PluginInstallOptions } from './pluginHosts.js';
2
2
  import { type PluginInstallStatus, type PluginRuntime } from './pluginRuntime.js';
3
+ import { type ZcodeMigrationReport } from './pluginZcodeMigration.js';
3
4
  export interface AgentPluginInstallResult {
4
5
  ok: boolean;
5
6
  status: PluginInstallStatus;
@@ -16,5 +17,7 @@ export interface AgentPluginInstallResult {
16
17
  installedPath?: string;
17
18
  error?: string;
18
19
  profile?: string;
20
+ migrated?: ZcodeMigrationReport;
21
+ warnings?: string[];
19
22
  }
20
23
  export declare function installAgentPlugin(runtime: PluginRuntime, options: PluginInstallOptions): Promise<AgentPluginInstallResult>;
@@ -5,6 +5,7 @@ import { inspectAgentPlugin, verifyPluginManifest } from './pluginInspection.js'
5
5
  import { hostLauncher } from './pluginLauncher.js';
6
6
  import { withPluginInstallLock } from './pluginLock.js';
7
7
  import { checkedPluginCommand, checkPluginHostVersion, PluginInstallError } from './pluginRuntime.js';
8
+ import { ZCODE_LOCAL_PLUGIN, ZCODE_MIGRATION_PREVIEW, ZCODE_MIGRATION_PREVIEW_NOTE, zcodeKeptMarketplaceWarning, zcodeMigrationPending, zcodeMigrationReport, zcodeMigrationSteps } from './pluginZcodeMigration.js';
8
9
  function trustInstruction(host) {
9
10
  return `${host.label} asks you to trust a plugin before it installs. Review ${AGENT_PLUGIN_REPOSITORY}, then rerun with --trust: evolver plugin install --host ${host.id} --trust`;
10
11
  }
@@ -19,6 +20,56 @@ function assertNoConflicts(inspection) {
19
20
  if (inspection.conflicts.length > 0)
20
21
  throw new PluginInstallError('conflict', inspection.conflicts.join('\n'), inspection.migrations);
21
22
  }
23
+ function dryRunResult(options, result, trustMissing) {
24
+ const { host } = options;
25
+ const zcode = host.id === 'zcode';
26
+ const commands = zcode ? [...zcodeMigrationSteps(options, ZCODE_MIGRATION_PREVIEW), ...result.commands] : result.commands;
27
+ const notes = [...(zcode ? [ZCODE_MIGRATION_PREVIEW_NOTE] : []), ...(trustMissing ? [trustInstruction(host)] : [])];
28
+ return { ...result, ok: true, status: 'dry_run', commands, instructions: [...result.instructions, ...notes, 'Preview only: host version, registration, download and installation have not been executed.'] };
29
+ }
30
+ function alreadyInstalled(runtime, options, result, inspection) {
31
+ if (!inspection.installed || zcodeMigrationPending(inspection.zcodeLocal))
32
+ return undefined;
33
+ const installedPath = verifyPluginManifest(runtime, options, inspection.installed);
34
+ const warnings = zcodeKeptMarketplaceWarning(inspection.zcodeLocal);
35
+ return { ...result, ok: true, status: 'already_installed', verified: true, version: inspection.installed.version, installedPath, commands: [], ...(warnings.length > 0 && { warnings }) };
36
+ }
37
+ function plannedCommands(options, inspection, install) {
38
+ if (!zcodeMigrationPending(inspection.zcodeLocal))
39
+ return install;
40
+ return [...zcodeMigrationSteps(options, inspection.zcodeLocal), ...(inspection.installed ? [] : install)];
41
+ }
42
+ async function runPlannedCommands(runtime, options, result, inspection, bundle) {
43
+ let installAnswer;
44
+ for (const step of result.commands) {
45
+ if (step.name === 'marketplace' && inspection.marketplacePresent)
46
+ continue;
47
+ const executed = await checkedPluginCommand(runtime, step.command, step.args, options.root, 120_000);
48
+ result.completed.push(step.name);
49
+ if (step.name === 'marketplace') {
50
+ const registered = await inspectAgentPlugin(runtime, options, bundle);
51
+ if (!registered.marketplacePresent || registered.conflicts.length > 0) {
52
+ throw new PluginInstallError('conflict', 'The registered marketplace could not be confirmed as the unified plugin source. No plugin install was attempted.');
53
+ }
54
+ }
55
+ else if (step.name === 'install') {
56
+ try {
57
+ installAnswer = JSON.parse(executed.stdout);
58
+ }
59
+ catch { /* Some native installers report human-readable progress; the final inventory is authoritative. */ }
60
+ }
61
+ }
62
+ return installAnswer;
63
+ }
64
+ function failureNotes(completed) {
65
+ if (completed.length === 0)
66
+ return [];
67
+ const removed = completed.includes('uninstall-local') ? `Only the ${ZCODE_LOCAL_PLUGIN} steps in completed removed anything; no other` : 'No existing';
68
+ return [
69
+ `Commands already completed: ${completed.join(', ')}. Inspect the selected host before retrying.`,
70
+ `${removed} plugin, user data or marketplace was automatically removed. Use the rollback instructions only after checking the current host registration.`,
71
+ ];
72
+ }
22
73
  function migrationInstructions(error) {
23
74
  if (!(error instanceof PluginInstallError) || error.instructions.length === 0)
24
75
  return [];
@@ -40,9 +91,8 @@ export async function installAgentPlugin(runtime, options) {
40
91
  return { ...result, status: 'manual_required', instructions: [...instructions, `Requested scope: ${options.scope}. No client configuration was changed.`] };
41
92
  }
42
93
  const trustMissing = host.requiresTrust && !options.trust;
43
- if (options.dryRun) {
44
- return { ...result, ok: true, status: 'dry_run', instructions: [...result.instructions, ...(trustMissing ? [trustInstruction(host)] : []), 'Preview only: host version, registration, download and installation have not been executed.'] };
45
- }
94
+ if (options.dryRun)
95
+ return dryRunResult(options, result, trustMissing);
46
96
  if (trustMissing) {
47
97
  return { ...result, status: 'trust_required', error: `${host.label} installs plugin hooks, MCP servers and skills only after you trust the plugin. No host command was run.`, instructions: [trustInstruction(host)] };
48
98
  }
@@ -51,46 +101,32 @@ export async function installAgentPlugin(runtime, options) {
51
101
  let bundle = host.kind === 'script' ? await useReleaseCheckout(runtime, options, result) : undefined;
52
102
  let inspection = await inspectAgentPlugin(runtime, options, bundle);
53
103
  assertNoConflicts(inspection);
54
- if (inspection.installed) {
55
- const installedPath = verifyPluginManifest(runtime, options, inspection.installed);
56
- return { ...result, ok: true, status: 'already_installed', verified: true, version: inspection.installed.version, installedPath, commands: [] };
57
- }
104
+ const settled = alreadyInstalled(runtime, options, result, inspection);
105
+ if (settled)
106
+ return settled;
58
107
  return await withPluginInstallLock(runtime, options, async () => {
59
108
  inspection = await inspectAgentPlugin(runtime, options, bundle);
60
109
  assertNoConflicts(inspection);
61
- if (inspection.installed) {
62
- const installedPath = verifyPluginManifest(runtime, options, inspection.installed);
63
- return { ...result, ok: true, status: 'already_installed', verified: true, version: inspection.installed.version, installedPath, commands: [] };
64
- }
110
+ const settledInLock = alreadyInstalled(runtime, options, result, inspection);
111
+ if (settledInLock)
112
+ return settledInLock;
65
113
  if (host.id === 'dsh')
66
114
  await assertDshProfileStoreMatches(runtime, options);
67
115
  if (host.kind === 'bundle')
68
116
  bundle = await useReleaseCheckout(runtime, options, result);
69
- let installAnswer;
70
- for (const step of result.commands) {
71
- if (step.name === 'marketplace' && inspection.marketplacePresent)
72
- continue;
73
- const executed = await checkedPluginCommand(runtime, step.command, step.args, options.root, 120_000);
74
- result.completed.push(step.name);
75
- if (step.name === 'marketplace') {
76
- inspection = await inspectAgentPlugin(runtime, options, bundle);
77
- if (!inspection.marketplacePresent || inspection.conflicts.length > 0) {
78
- throw new PluginInstallError('conflict', 'The registered marketplace could not be confirmed as the unified plugin source. No plugin install was attempted.');
79
- }
80
- }
81
- else {
82
- try {
83
- installAnswer = JSON.parse(executed.stdout);
84
- }
85
- catch { /* Some native installers report human-readable progress; the final inventory is authoritative. */ }
86
- }
87
- }
117
+ const local = inspection.zcodeLocal;
118
+ result.commands = plannedCommands(options, inspection, result.commands);
119
+ const installAnswer = await runPlannedCommands(runtime, options, result, inspection, bundle);
88
120
  inspection = await inspectAgentPlugin(runtime, options, bundle);
89
121
  assertNoConflicts(inspection);
90
122
  if (!inspection.installed)
91
123
  throw new PluginInstallError('failed', `The ${AGENT_PLUGIN_NAME} command completed, but the selected host/scope did not register it. Installation was not confirmed.`);
92
124
  const installedPath = verifyPluginManifest(runtime, options, inspection.installed, installAnswer);
93
- return { ...result, ok: true, status: 'installed', verified: true, version: inspection.installed.version, installedPath };
125
+ const warnings = zcodeKeptMarketplaceWarning(local);
126
+ return {
127
+ ...result, ok: true, status: result.completed.includes('install') ? 'installed' : 'already_installed', verified: true, version: inspection.installed.version, installedPath,
128
+ ...zcodeMigrationReport(local, result.completed), ...(warnings.length > 0 && { warnings }),
129
+ };
94
130
  });
95
131
  }
96
132
  catch (error) {
@@ -98,10 +134,7 @@ export async function installAgentPlugin(runtime, options) {
98
134
  ...result,
99
135
  status: error instanceof PluginInstallError ? error.status : 'failed',
100
136
  error: error instanceof PluginInstallError ? error.message : 'The plugin operation failed; no verified installation was reported.',
101
- instructions: [...result.instructions, ...migrationInstructions(error), ...(result.completed.length > 0 ? [
102
- `Commands already completed: ${result.completed.join(', ')}. Inspect the selected host before retrying.`,
103
- 'No existing plugin, user data or marketplace was automatically removed. Use the rollback instructions only after checking the current host registration.',
104
- ] : [])],
137
+ instructions: [...result.instructions, ...migrationInstructions(error), ...failureNotes(result.completed)],
105
138
  };
106
139
  }
107
140
  }
@@ -0,0 +1,22 @@
1
+ import { type PluginCommandStep, type PluginHost, type PluginInstallOptions } from './pluginHosts.js';
2
+ import { type PluginRuntime } from './pluginRuntime.js';
3
+ export declare const ZCODE_LOCAL_PLUGIN = "evolver-plugin@evolver-zcode-local";
4
+ /** A ZCode local-folder install of this plugin, which would run the same hooks as the evomap install. */
5
+ export interface ZcodeLocalInstall {
6
+ uninstall?: string;
7
+ removeMarketplace?: string;
8
+ keptMarketplace?: string;
9
+ }
10
+ export interface ZcodeMigrationReport {
11
+ uninstalled?: string;
12
+ removedMarketplace?: string;
13
+ }
14
+ export declare function zcodeLocalInstall(runtime: PluginRuntime, host: PluginHost, pluginIds: readonly string[], markets: readonly Record<string, unknown>[]): ZcodeLocalInstall | undefined;
15
+ export declare const zcodeMigrationPending: (local: ZcodeLocalInstall | undefined) => boolean;
16
+ export declare function zcodeMigrationSteps(options: PluginInstallOptions, local: ZcodeLocalInstall): PluginCommandStep[];
17
+ export declare const ZCODE_MIGRATION_PREVIEW: ZcodeLocalInstall;
18
+ export declare const ZCODE_MIGRATION_PREVIEW_NOTE = "uninstall-local and remove-local-marketplace run only when evolver-plugin@evolver-zcode-local is installed or its marketplace points into Evolver's release cache.";
19
+ export declare function zcodeMigrationReport(local: ZcodeLocalInstall | undefined, completed: readonly string[]): {
20
+ migrated?: ZcodeMigrationReport;
21
+ };
22
+ export declare function zcodeKeptMarketplaceWarning(local: ZcodeLocalInstall | undefined): string[];
@@ -0,0 +1,40 @@
1
+ import { isManagedPackedBundle } from './pluginBundle.js';
2
+ import { AGENT_PLUGIN_NAME, ZCODE_LOCAL_MARKETPLACE } from './pluginHosts.js';
3
+ import { objectOf } from './pluginRuntime.js';
4
+ export const ZCODE_LOCAL_PLUGIN = `${AGENT_PLUGIN_NAME}@${ZCODE_LOCAL_MARKETPLACE}`;
5
+ function ownsLocalMarketplace(runtime, host, record) {
6
+ const source = objectOf(record['source']);
7
+ const folder = source?.['source'] === 'directory' ? source['path'] : undefined;
8
+ return typeof folder === 'string' && isManagedPackedBundle(runtime, host, folder);
9
+ }
10
+ export function zcodeLocalInstall(runtime, host, pluginIds, markets) {
11
+ const installed = pluginIds.includes(ZCODE_LOCAL_PLUGIN);
12
+ const market = markets.find(record => record['name'] === ZCODE_LOCAL_MARKETPLACE);
13
+ if (!installed && !market)
14
+ return undefined;
15
+ const marketplace = market && (ownsLocalMarketplace(runtime, host, market) ? { removeMarketplace: ZCODE_LOCAL_MARKETPLACE } : { keptMarketplace: ZCODE_LOCAL_MARKETPLACE });
16
+ return { ...(installed && { uninstall: ZCODE_LOCAL_PLUGIN }), ...marketplace };
17
+ }
18
+ export const zcodeMigrationPending = (local) => Boolean(local?.uninstall || local?.removeMarketplace);
19
+ export function zcodeMigrationSteps(options, local) {
20
+ const [command = '', ...prefix] = options.launcher;
21
+ const step = (name, args) => ({ name, command, args: [...prefix, ...args] });
22
+ return [
23
+ ...(local.uninstall ? [step('uninstall-local', ['plugins', 'uninstall', local.uninstall, '--scope', options.scope, '--keep-data', '--force', '--json'])] : []),
24
+ ...(local.removeMarketplace ? [step('remove-local-marketplace', ['plugins', 'marketplace', 'remove', local.removeMarketplace, '--json'])] : []),
25
+ ];
26
+ }
27
+ export const ZCODE_MIGRATION_PREVIEW = { uninstall: ZCODE_LOCAL_PLUGIN, removeMarketplace: ZCODE_LOCAL_MARKETPLACE };
28
+ export const ZCODE_MIGRATION_PREVIEW_NOTE = `uninstall-local and remove-local-marketplace run only when ${ZCODE_LOCAL_PLUGIN} is installed or its marketplace points into Evolver's release cache.`;
29
+ export function zcodeMigrationReport(local, completed) {
30
+ const migrated = {
31
+ ...(completed.includes('uninstall-local') && { uninstalled: local?.uninstall }),
32
+ ...(completed.includes('remove-local-marketplace') && { removedMarketplace: local?.removeMarketplace }),
33
+ };
34
+ return Object.keys(migrated).length > 0 ? { migrated } : {};
35
+ }
36
+ export function zcodeKeptMarketplaceWarning(local) {
37
+ if (!local?.keptMarketplace)
38
+ return [];
39
+ return [`Marketplace ${local.keptMarketplace} points at a folder Evolver does not manage, so it stays registered. Do not install ${AGENT_PLUGIN_NAME} from it as well: both copies would run the same hooks.`];
40
+ }
@@ -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.52",
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.52",
31
- "@evomap/evolver-adapter-public": "2.0.52",
32
- "@evomap/evolver-mcp": "2.0.52",
33
- "@evomap/evolver-proxy": "2.0.52",
34
- "@evomap/evolver-runtime-adapters": "2.0.52",
35
- "@evomap/evolver-webui": "2.0.52"
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",