@craft_eco/craft-mcp 0.1.34-beta.2 → 0.1.34-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +6 -17
  2. package/bin/craft-mcp.mjs +30 -2
  3. package/dist-server/core/upload-limits.mjs +11 -0
  4. package/dist-server/game-workflow/bundle-files.mjs +6 -1
  5. package/dist-server/game-workflow/engines.mjs +18 -9
  6. package/dist-server/game-workflow/project-context.mjs +11 -7
  7. package/dist-server/game-workflow/project-install.mjs +17 -8
  8. package/dist-server/game-workflow/projects.mjs +13 -3
  9. package/dist-server/integrations/config.mjs +41 -18
  10. package/dist-server/integrations/connect.mjs +18 -9
  11. package/dist-server/integrations/connection-handoff.mjs +9 -8
  12. package/dist-server/integrations/distribution-targets.mjs +9 -0
  13. package/dist-server/integrations/dsh-config.mjs +30 -14
  14. package/dist-server/integrations/fixed-launcher.mjs +1 -0
  15. package/dist-server/integrations/host-config-scope.mjs +4 -3
  16. package/dist-server/integrations/hosts.mjs +3 -1
  17. package/dist-server/integrations/install.mjs +147 -43
  18. package/dist-server/integrations/installation-state.mjs +2 -1
  19. package/dist-server/integrations/instance-skill.mjs +26 -0
  20. package/dist-server/integrations/instance.mjs +29 -0
  21. package/dist-server/integrations/launcher-start.mjs +6 -6
  22. package/dist-server/integrations/login-task-command.mjs +3 -3
  23. package/dist-server/integrations/opencode-config.mjs +13 -6
  24. package/dist-server/integrations/project-setup.mjs +48 -18
  25. package/dist-server/integrations/runtime-candidate.mjs +32 -6
  26. package/dist-server/integrations/runtime-file-diagnostics.mjs +68 -0
  27. package/dist-server/integrations/runtime-gc.mjs +8 -2
  28. package/dist-server/integrations/runtime-identity.mjs +56 -8
  29. package/dist-server/integrations/runtime.mjs +7 -3
  30. package/dist-server/integrations/uninstall.mjs +160 -0
  31. package/dist-server/integrations/updates.mjs +57 -42
  32. package/dist-server/launcher.mjs +65 -10
  33. package/dist-server/mcp/production-events.mjs +52 -29
  34. package/dist-server/mcp/server.mjs +18 -9
  35. package/dist-server/mcp/update-session.mjs +9 -6
  36. package/dist-server/preview/preview-snapshot.mjs +3 -2
  37. package/package.json +5 -3
  38. package/resources/craft-create/SKILL.md +2 -0
  39. package/resources/craft-update/SKILL.md +2 -0
  40. package/vendor/craft-runtime/NOTICE.md +1 -1
  41. package/vendor/craft-runtime/SOURCE.json +9 -5
  42. package/vendor/craft-runtime/index.js +228 -164
  43. package/vendor/craft-runtime/package.json +1 -1
@@ -3,6 +3,7 @@ import { readFileSync, readdirSync, lstatSync, realpathSync } from 'node:fs';
3
3
  import { isDeepStrictEqual } from 'node:util';
4
4
  import { isAlias, isMap, isSeq, parseDocument } from 'yaml';
5
5
  import { hasCraftConnectionIdentity } from './registration-identity.mjs';
6
+ import { registrationsForInstance } from './instance.mjs';
6
7
 
7
8
  const pluginName = '@deepseek-ai/dsh-mcp-client';
8
9
  const pluginId = 'mcp-craft';
@@ -37,7 +38,7 @@ function hasDynamicNode(node) {
37
38
  }
38
39
 
39
40
  function candidates(document) {
40
- const rows = [], identities = new Set(), allIds = new Map();
41
+ const rows = [], identities = new Set(), allNames = new Map(), allIds = new Map();
41
42
  const values = document.toJS();
42
43
  for (const [patchIndex, patch] of document.contents.items.entries()) {
43
44
  if (!isMap(patch)) throw new Error('DSH patch entries must be YAML mappings');
@@ -48,6 +49,10 @@ function candidates(document) {
48
49
  if (!isMap(node)) throw new Error('DSH plugin entries must be YAML mappings');
49
50
  const value = insert ? values[patchIndex].insert[entryIndex] : values[patchIndex];
50
51
  if (typeof value.id === 'string') allIds.set(value.id, (allIds.get(value.id) ?? 0) + 1);
52
+ if (value.name === pluginName && typeof value.config?.serverName === 'string') {
53
+ const name = value.config.serverName;
54
+ allNames.set(name, (allNames.get(name) ?? 0) + 1);
55
+ }
51
56
  if (!isCraft(value)) continue;
52
57
  if (!insert || patch.items.some(pair => pair.key?.value !== 'insert')) {
53
58
  throw new Error('Ambiguous Craft DSH patch: use one complete insert registration without additional patch operations');
@@ -61,12 +66,12 @@ function candidates(document) {
61
66
  if (value.disabled !== undefined && typeof value.disabled !== 'boolean') throw new Error('Craft DSH disabled must be a boolean');
62
67
  if (identities.has(value.id)) throw new Error('Duplicate Craft DSH plugin id');
63
68
  identities.add(value.id);
64
- rows.push({ node, value });
69
+ rows.push({ node, value, patchIndex, insert, entryIndex });
65
70
  }
66
71
  }
67
- if (rows.length > 1) throw new Error('Multiple Craft DSH registrations found; keep one registration before installing');
68
72
  for (const { value } of rows) {
69
73
  if (allIds.get(value.id) > 1) throw new Error('Ambiguous or duplicate Craft DSH plugin id');
74
+ if (allNames.get(value.config.serverName) > 1) throw new Error('Duplicate Craft DSH server name: ' + value.config.serverName);
70
75
  }
71
76
  // A later id-only patch could silently override or disable the inserted server.
72
77
  for (const patch of document.contents.items) {
@@ -87,7 +92,7 @@ export function dshRegistrations(text) {
87
92
  return candidates(documentFor(text)).map(({ value }) => ({ name: value.config.serverName, connection: connectionFor(value) }));
88
93
  }
89
94
 
90
- function connectionConfig(connection, previous = {}) {
95
+ function connectionConfig(connection, previous = {}, serverId) {
91
96
  if (!isRecord(connection) || typeof connection.command !== 'string' || !connection.command.trim() ||
92
97
  !Array.isArray(connection.args) || connection.args.some(arg => typeof arg !== 'string') ||
93
98
  (connection.env !== undefined && (!isRecord(connection.env) || Object.values(connection.env).some(value => typeof value !== 'string')))) {
@@ -96,7 +101,7 @@ function connectionConfig(connection, previous = {}) {
96
101
  if (previous.env !== undefined && (!isRecord(previous.env) || Object.values(previous.env).some(value => typeof value !== 'string'))) {
97
102
  throw new Error('Invalid existing Craft DSH environment');
98
103
  }
99
- const next = { ...previous, ...connection, serverName: 'craft', transport: 'stdio', env: { ...previous.env, ...connection.env } };
104
+ const next = { ...previous, ...connection, serverName: serverId, transport: 'stdio', env: { ...previous.env, ...connection.env } };
100
105
  next.startupTimeoutMs ??= connection.timeout ?? (connection.startup_timeout_sec ? connection.startup_timeout_sec * 1000 : 120000);
101
106
  next.toolCallTimeoutMs ??= 3600000;
102
107
  next.failOnStartupError ??= true;
@@ -105,14 +110,15 @@ function connectionConfig(connection, previous = {}) {
105
110
  }
106
111
 
107
112
  /** Merge a single owned stdio registration while retaining unrelated YAML nodes. */
108
- export function mergeDshConfig(text, connection, { previousName = 'craft', enable = true } = {}) {
113
+ export function mergeDshConfig(text, connection, { serverId = 'craft', previousName = serverId, enable = true } = {}) {
109
114
  const document = documentFor(text), found = candidates(document);
110
115
  const previous = found.find(row => row.value.config.serverName === previousName);
111
- if (found.length && !previous) throw new Error('Craft DSH installation conflicts with an existing registration');
112
- if (!previous && previousName !== 'craft') throw new Error('Previous Craft DSH registration was not found');
113
- const config = connectionConfig(connection, previous?.value.config);
116
+ const id = 'mcp-' + serverId;
117
+ if (found.some(row => row !== previous && (row.value.id === id || row.value.config.serverName === serverId))) throw new Error('Craft DSH installation conflicts with an existing registration');
118
+ if (!previous && previousName !== serverId) throw new Error('Previous Craft DSH registration was not found');
119
+ const config = connectionConfig(connection, previous?.value.config, serverId);
114
120
  if (!previous) {
115
- document.contents.items.push(document.createNode({ insert: [{ id: pluginId, name: pluginName, config }] }));
121
+ document.contents.items.push(document.createNode({ insert: [{ id, name: pluginName, config }] }));
116
122
  } else {
117
123
  const next = { ...previous.value, config };
118
124
  if (enable && next.disabled === true) next.disabled = false;
@@ -134,13 +140,22 @@ export function mergeDshConfig(text, connection, { previousName = 'craft', enabl
134
140
  }
135
141
  document.contents.flow = false;
136
142
  const output = document.toString({ lineWidth: 0 });
137
- const written = dshRegistrations(output);
138
- if (written.length !== 1 || written[0].name !== 'craft' || !isDeepStrictEqual(written[0].connection, connectionFor({ config, disabled: !enable && previous?.value.disabled === true }))) {
143
+ const written = dshRegistrations(output).find(row => row.name === serverId);
144
+ if (!written || !isDeepStrictEqual(written.connection, connectionFor({ config, disabled: !enable && previous?.value.disabled === true }))) {
139
145
  throw new Error('Generated Craft DSH configuration failed validation');
140
146
  }
141
147
  return output;
142
148
  }
143
149
 
150
+ export function removeDshConfig(text, serverId) {
151
+ const document = documentFor(text);
152
+ const row = candidates(document).find(entry => entry.value.config.serverName === serverId);
153
+ if (!row) return text;
154
+ if (row.insert.items.length === 1) document.contents.delete(row.patchIndex);
155
+ else row.insert.delete(row.entryIndex);
156
+ return document.toString({ lineWidth: 0 });
157
+ }
158
+
144
159
  /** Read-only profile inventory; callers decide how to handle an existing scope. */
145
160
  export function inspectDshProfiles(dshHome) {
146
161
  const profiles = path.join(dshHome, 'profiles');
@@ -175,8 +190,9 @@ export function inspectDshProfiles(dshHome) {
175
190
  }
176
191
 
177
192
  /** Shared install/doctor/update guard; never move profile-owned registrations. */
178
- export function assertDshSharedScope(paths) {
193
+ export function assertDshSharedScope(paths, serverId = 'craft') {
179
194
  if (!paths.dshHome) return;
180
- const profiles = inspectDshProfiles(paths.dshHome);
195
+ const profiles = inspectDshProfiles(paths.dshHome).filter(profile =>
196
+ profile.registrations.some(row => row.name === serverId) || registrationsForInstance(profile.registrations, serverId).length);
181
197
  if (profiles.length) throw new Error('DSH already has a profile-scoped Craft registration: ' + profiles.map(profile => profile.path).join(', ') + '. Preserve it and resolve that registration before installing or checking the shared DSH_HOME configuration; a duplicate MCP was not created.');
182
198
  }
@@ -20,6 +20,7 @@ export async function planLauncher(installationFile, previous, packageRoot) {
20
20
  }
21
21
 
22
22
  export async function verifyLauncher(state, installationFile, connection) {
23
+ if (connection?.env && (connection.env.CRAFT_SERVER_ID ?? 'craft') !== state.server_id) throw new Error('Craft launcher instance differs from its registration');
23
24
  if (!state.launcher) return { mode: 'legacy_versioned_entry' };
24
25
  const expected = launcherPath(installationFile);
25
26
  if (state.launcher.schema !== 1 || state.launcher.entry !== expected || !/^[a-f0-9]{64}$/.test(state.launcher.sha256 ?? '')) throw new Error('Invalid Craft fixed launcher identity');
@@ -1,16 +1,17 @@
1
1
  import path from 'node:path';
2
2
  import {optionalFile,assertPlainPath} from './files.mjs';
3
- import {craftRegistrations} from './config.mjs';
3
+ import {craftConfig,craftRegistrations} from './config.mjs';
4
+ import { registrationsForInstance } from './instance.mjs';
4
5
 
5
6
  // OpenCode loads both user JSON and JSONC. Updating one file cannot silently
6
7
  // ignore a Craft registration in the other, even if that declaration is disabled.
7
- export async function assertHostConfigScope(config, host, peers = []) {
8
+ export async function assertHostConfigScope(config, host, peers = [], serverId = 'craft') {
8
9
  if(host!=='opencode') return;
9
10
  for(const peer of new Set([...peers,...['opencode.json','opencode.jsonc'].map(name=>path.join(path.dirname(config),name))])) {
10
11
  if(typeof peer!=='string'||!path.isAbsolute(peer)) throw new Error('Invalid additional host configuration path');
11
12
  if(path.resolve(peer)===path.resolve(config)) continue;
12
13
  await assertPlainPath(peer);
13
14
  const text=await optionalFile(peer);
14
- if(text!==null && craftRegistrations(text,'opencode').length) throw new Error('OpenCode also loads a Craft registration from '+peer+'; preserve both files and consolidate the intended Craft registration before installing or updating');
15
+ if(text!==null && (craftConfig(text,'opencode',serverId) !== undefined || registrationsForInstance(craftRegistrations(text,'opencode'),serverId).length)) throw new Error('OpenCode also loads a Craft registration from '+peer+'; preserve both files and consolidate the intended Craft registration before installing or updating');
15
16
  }
16
17
  }
@@ -1,5 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import { existsSync } from 'node:fs';
3
+ import { validateServerId } from './instance.mjs';
3
4
 
4
5
  export const hosts = Object.freeze({
5
6
  codex: { label: 'Codex', config: '.codex/config.toml', skills: '.agents/skills', projectSkills: '.agents/skills', format: 'toml' },
@@ -47,6 +48,7 @@ export function hostCommandOptions(options = {}, env = process.env) {
47
48
  export function hostPaths(home, ide, codexHome, options = {}) {
48
49
  const host = hosts[clientIde(ide)];
49
50
  if (!host) throw new Error('Select a host before installing');
51
+ const serverId = validateServerId(options.serverId ?? 'craft');
50
52
  if (codexHome && !path.isAbsolute(codexHome)) throw new Error('CODEX_HOME must be absolute');
51
53
  let override = ide === 'claude' ? options.claudeConfigDir : ide === 'dsh' ? options.dshHome : ide === 'kimi' ? options.kimiCodeHome : ide === 'qwen' ? options.qwenHome : undefined;
52
54
  if (ide === 'dsh' && typeof override === 'string') {
@@ -73,7 +75,7 @@ export function hostPaths(home, ide, codexHome, options = {}) {
73
75
  ? ['.codebuddy/.mcp.json','.codebuddy/mcp.json','.codebuddy.json'].map(file=>path.join(home,file)).find(file=>existsSync(file)) ?? path.join(home,host.config)
74
76
  : ide === 'codex' && codexHome ? path.join(codexHome,'config.toml')
75
77
  : override ? path.join(override, ({ claude: '.claude.json', dsh: 'cordis.patch.yml', kimi: 'mcp.json', qwen: 'settings.json' })[ide]) : path.join(home,host.config));
76
- return { config, skill: path.join(skillsRoot, 'craft-create', 'SKILL.md'), updateSkill: path.join(skillsRoot, 'craft-update', 'SKILL.md'),
78
+ return { config, skill: path.join(skillsRoot, serverId + '-create', 'SKILL.md'), updateSkill: path.join(skillsRoot, serverId + '-update', 'SKILL.md'),
77
79
  ...(ide==='opencode'?{configPeers:[...new Set([path.join(opencodeRoot,'opencode.json'),path.join(opencodeRoot,'opencode.jsonc'),options.opencodeConfig].filter(file=>file&&path.resolve(file)!==path.resolve(config)))]}:{}),
78
80
  ...(ide === 'zcode' ? { fallbackConfig: path.join(home, '.agents/mcp.json') } : {}),
79
81
  ...(ide === 'dsh' ? { dshHome: override || path.join(home, '.dsh') } : {}) };
@@ -1,6 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import os from 'node:os';
3
- import { readFile, mkdir } from 'node:fs/promises';
3
+ import { readFile, mkdir, realpath } from 'node:fs/promises';
4
4
  import lockfile from 'proper-lockfile';
5
5
  import { defaultProfileDataDir, getAppDataRoot } from '../core/app-paths.mjs';
6
6
  import { hostPaths, hostCommandOptions, installTargets } from './hosts.mjs';
@@ -16,8 +16,51 @@ import { planLauncher, verifyLauncher } from './fixed-launcher.mjs';
16
16
  import { prepareRuntimeCandidate, refreshRuntimeCandidate, publishRuntimeCandidate, disposeRuntimeCandidate } from './runtime-candidate.mjs';
17
17
  import { sameInstallation, installationChanged } from './installation-transaction.mjs';
18
18
  import { assertHostConfigScope } from './host-config-scope.mjs';
19
+ import { registrationsForInstance, serverIdForChannel, validateServerId } from './instance.mjs';
20
+ import { renderInstanceSkill } from './instance-skill.mjs';
21
+ import { verifyRuntimeProductFiles } from './runtime-file-diagnostics.mjs';
19
22
 
20
23
  const bootstrapMarker = '<!-- craft-mcp:bootstrap:v1 -->';
24
+
25
+ async function canonicalWorkspace(directory) {
26
+ try { return await realpath(directory); }
27
+ catch (error) {
28
+ const parent = path.dirname(directory);
29
+ if (error.code !== 'ENOENT' || parent === directory) throw error;
30
+ return path.join(await canonicalWorkspace(parent), path.basename(directory));
31
+ }
32
+ }
33
+
34
+ async function checkSiblingWorkspaces(registrations, previousName, host, workspace) {
35
+ const siblings = registrations.filter(({ name, connection }) => name !== previousName &&
36
+ connection?.env?.CRAFT_INSTALLATION_FILE && connection.env.CRAFT_CLIENT_IDE === host);
37
+ if (!siblings.length) return;
38
+ const selected = await canonicalWorkspace(workspace);
39
+ for (const { name, connection } of siblings) {
40
+ const args = connection.args ?? [], index = args.indexOf('--workspace');
41
+ const roots = [connection.env.CLIENT_WORKSPACE_ROOT, index >= 0 ? args[index + 1] : undefined];
42
+ for (const root of new Set(roots.filter(value => typeof value === 'string' && path.isAbsolute(value)))) {
43
+ if (path.relative(selected, await canonicalWorkspace(root)) === '') {
44
+ throw new Error('Craft workspace already belongs to another instance in ' + host + ': ' + name + '. Select a separate game directory.');
45
+ }
46
+ }
47
+ }
48
+ }
49
+
50
+ function checkInstanceBinding(state, host, paths, serverId, installationFile) {
51
+ if (state.host !== host || path.relative(state.config, paths.config) !== '' || state.server_id !== serverId) {
52
+ throw new Error('Craft installation state belongs to another host configuration or instance');
53
+ }
54
+ const expected = installationPath(path.dirname(installationFile), host, paths.config, serverId);
55
+ if (serverId !== 'craft' && (state.id !== expected.id || path.relative(installationFile, expected.file) !== '')) {
56
+ throw new Error('Craft instance installation path differs from its registration');
57
+ }
58
+ if (serverId !== 'craft' && state.skills && (path.relative(state.skills['craft-create'], paths.skill) !== '' ||
59
+ (state.skills['craft-update'] && path.relative(state.skills['craft-update'], paths.updateSkill) !== ''))) {
60
+ throw new Error('Craft installation Skill paths differ from the selected host configuration');
61
+ }
62
+ }
63
+
21
64
  function legacyNpmSource(connection, packageName) {
22
65
  const args = connection?.args ?? [];
23
66
  const spec = args.find(value => typeof value === 'string' && (value === packageName || value.startsWith(packageName + '@')));
@@ -57,9 +100,13 @@ function hostRuntimeEnvironment(host, existing = {}) {
57
100
 
58
101
  export async function installHosts({ ide, workspace, platform, packageRoot, home = os.homedir(), codexHome, hostOptions = {},
59
102
  runtimeRoot = path.join(getAppDataRoot(), 'runtimes'), stateRoot = path.join(path.dirname(runtimeRoot), 'installations'),
60
- registry, channel, updates, selector = 'package', onlyIfMissing = false, materialize = stageRuntime, probe = probeRuntime,
103
+ registry, channel, updates, serverId, selector = 'package', repair = false, onlyIfMissing = false, materialize = stageRuntime, probe = probeRuntime,
61
104
  lookup = queryRegistry, materializeRegistry = stageRegistryRuntime }) {
62
105
  const targets = installTargets(ide);
106
+ const instance = validateServerId(serverId ?? 'craft');
107
+ if (repair && (targets.length !== 1 || [workspace, platform, registry, channel, updates].some(value => value !== undefined))) {
108
+ throw new Error('Repair uses one existing installation and its recorded settings. Select it with --ide and --instance.');
109
+ }
63
110
  if (hostOptions.configPath && targets.length !== 1) throw new Error('--host-config requires exactly one --ide');
64
111
  if (workspace !== undefined && !path.isAbsolute(workspace)) throw new Error('--workspace must be absolute');
65
112
  if (platform !== undefined) platform = platformOrigin(platform);
@@ -67,14 +114,14 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
67
114
  if (updates !== undefined && !['auto', 'off'].includes(updates)) throw new Error('--updates must be auto or off');
68
115
  const pkg = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
69
116
  await mkdir(runtimeRoot, { recursive: true });
70
- const targetPaths = new Map(targets.map(host => [host, hostPaths(home, host, codexHome, hostOptions)]));
117
+ const targetPaths = new Map(targets.map(host => [host, hostPaths(home, host, codexHome, { ...hostOptions, serverId: instance })]));
71
118
  async function readPlans() {
72
119
  const plans = [];
73
120
  for (const host of targets) {
74
121
  const paths = targetPaths.get(host);
75
122
  await assertPlainPath(paths.config); await assertPlainPath(paths.skill); await assertPlainPath(paths.updateSkill);
76
- assertDshSharedScope(paths);
77
- await assertHostConfigScope(paths.config,host,paths.configPeers);
123
+ assertDshSharedScope(paths, instance);
124
+ await assertHostConfigScope(paths.config,host,paths.configPeers,instance);
78
125
  const original = await optionalFile(paths.config), existingSkill = await optionalFile(paths.skill);
79
126
  let configInput = original ?? '', fallbackSnapshot;
80
127
  if (paths.fallbackConfig) {
@@ -85,15 +132,27 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
85
132
  }
86
133
  const existingUpdateSkill = await optionalFile(paths.updateSkill);
87
134
  if (existingSkill && !existingSkill.includes(bootstrapMarker)) throw new Error('User-owned craft-create Skill preserved; rename it before installing: ' + paths.skill);
88
- const registrations = craftRegistrations(configInput, host);
135
+ const hostRegistrations = craftRegistrations(configInput, host);
136
+ const registrations = registrationsForInstance(hostRegistrations, instance);
137
+ if (instance !== 'craft' && craftConfig(configInput, host, instance) !== undefined && !registrations.some(entry => entry.name === instance)) {
138
+ throw new Error('The requested Craft instance name is already used by another registration: ' + instance);
139
+ }
89
140
  if (onlyIfMissing && registrations.length) throw new Error(host + ': Craft was configured while project setup was running; preserve the registration and inspect it again');
90
141
  if (registrations.length > 1) throw new Error(host + ': Multiple Craft registrations found; preserve separate environments and select one installation before updating');
91
- const previousName = registrations[0]?.name ?? 'craft', old = registrations[0]?.connection;
142
+ const previousName = registrations[0]?.name ?? instance, old = registrations[0]?.connection;
92
143
  const legacySource = legacyNpmSource(old, pkg.name);
93
- const statePath = installationPath(stateRoot, host, paths.config);
144
+ const statePath = installationPath(stateRoot, host, paths.config, instance);
94
145
  const previousSnapshot = old?.env?.CRAFT_INSTALLATION_FILE ? await readInstallationSnapshot(old.env.CRAFT_INSTALLATION_FILE) : null;
95
146
  const previousState = previousSnapshot?.state;
96
- if (previousState && (previousState.host !== host || path.resolve(previousState.config) !== path.resolve(paths.config))) throw new Error('Craft installation state belongs to another host configuration');
147
+ if (repair && (previousState?.schema !== 2 || path.relative(runtimeRoot, previousState.runtime_root) !== '')) {
148
+ throw new Error('Repair requires the selected managed Craft installation and its original runtime root.');
149
+ }
150
+ if (previousState) checkInstanceBinding(previousState, host, paths, instance, old.env.CRAFT_INSTALLATION_FILE);
151
+ if (instance !== 'craft' && previousState && path.relative(old.env.CRAFT_INSTALLATION_FILE, statePath.file) !== '') throw new Error('Craft instance installation root differs from its registration');
152
+ const previousChannel = previousState?.source.channel ?? legacySource?.channel;
153
+ if (serverId !== undefined && previousChannel && channel && previousChannel !== channel) {
154
+ throw new Error('Craft instance ' + instance + ' already tracks ' + previousChannel + '; preserve that installation and use a different instance for ' + channel);
155
+ }
97
156
  const stateBefore = previousSnapshot && path.resolve(old.env.CRAFT_INSTALLATION_FILE) === path.resolve(statePath.file) ? previousSnapshot.text : await optionalFile(statePath.file);
98
157
  let previousRuntime = previousState?.target;
99
158
  if (!previousRuntime && old?.args?.[0] && path.isAbsolute(old.args[0])) {
@@ -106,10 +165,15 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
106
165
  if (pinned) previousRuntime = { version: pinned.slice('@craft_eco/craft-mcp@'.length) };
107
166
  }
108
167
  const workspaceIndex = old?.args?.indexOf('--workspace') ?? -1;
109
- const games = workspace ?? (workspaceIndex >= 0 ? old.args[workspaceIndex + 1] : old?.env?.CLIENT_WORKSPACE_ROOT) ?? path.join(home, 'CraftGames');
168
+ const defaultGames = instance === 'craft' ? path.join(home, 'CraftGames') : path.join(home, 'CraftTestGames', instance);
169
+ const games = workspace ?? (workspaceIndex >= 0 ? old.args[workspaceIndex + 1] : old?.env?.CLIENT_WORKSPACE_ROOT) ?? defaultGames;
110
170
  if (!path.isAbsolute(games)) throw new Error('Configured Craft workspace must be absolute');
171
+ await checkSiblingWorkspaces(hostRegistrations, previousName, host, path.resolve(games));
111
172
  const origin = platformOrigin(platform ?? old?.env?.CRAFT_WEB_URL ?? pkg.craft?.platform);
112
- const selection = installSource(pkg, { registry, channel, selector }, previousState, legacySource);
173
+ // A bare npx bootstrap can come from npm's latest tag. For a new primary
174
+ // installation the product follows stable; a legacy installation keeps its channel.
175
+ const selectedChannel = channel ?? (serverId === 'craft' && selector === 'bare' && !previousChannel ? 'stable' : undefined);
176
+ const selection = installSource(pkg, { registry, channel: selectedChannel, selector }, previousState, legacySource);
113
177
  plans.push({ host, paths, original, configInput, fallbackSnapshot, existingSkill, existingUpdateSkill, previousName, previousRuntime, previousState, legacySource, statePath, stateBefore, workspace: path.resolve(games), platform: origin, ...selection });
114
178
  }
115
179
  if (channel && plans.some(plan => plan.followTag)) {
@@ -125,8 +189,9 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
125
189
  await assertPlainPath(file);
126
190
  if (await optionalFile(file) !== expected) throw installationChanged('Craft host files changed while the candidate was prepared');
127
191
  }
128
- assertDshSharedScope(plan.paths);
129
- await assertHostConfigScope(plan.paths.config,plan.host,plan.paths.configPeers);
192
+ assertDshSharedScope(plan.paths, instance);
193
+ await assertHostConfigScope(plan.paths.config,plan.host,plan.paths.configPeers,instance);
194
+ await checkSiblingWorkspaces(craftRegistrations(plan.configInput, plan.host), plan.previousName, plan.host, plan.workspace);
130
195
  if (plan.fallbackSnapshot && await optionalFile(plan.fallbackSnapshot.file) !== plan.fallbackSnapshot.text) throw new Error('ZCode fallback MCP configuration changed during installation; retry without changing the fallback');
131
196
  const text = await optionalFile(plan.statePath.file);
132
197
  if (text !== plan.stateBefore) {
@@ -148,7 +213,18 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
148
213
  const candidates = new Map(), releases = new Map();
149
214
  async function preparePlan(plan) {
150
215
  let remote;
151
- if (plan.followTag) {
216
+ if (repair) {
217
+ const target = plan.previousRuntime;
218
+ if (target.origin?.kind === 'npm') {
219
+ if (registryOrigin(target.origin.registry) !== plan.source.registry || !target.origin.integrity) throw new Error('Recorded Craft repair source or integrity is inconsistent');
220
+ remote = { package: target.package, version: target.version, integrity: target.origin.integrity };
221
+ } else if (selector !== 'package' || pkg.version !== target.version) {
222
+ remote = await lookup({ ...plan.source, channel: target.version });
223
+ if (remote.package !== target.package || remote.version !== target.version || !remote.integrity) {
224
+ throw new Error('Could not resolve the exact Craft version for repair; use the original installation package.');
225
+ }
226
+ }
227
+ } else if (plan.followTag) {
152
228
  const key = JSON.stringify(plan.source);
153
229
  if (!releases.has(key)) releases.set(key, await lookup(plan.source));
154
230
  remote = releases.get(key);
@@ -159,7 +235,7 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
159
235
  if (!candidates.has(key)) {
160
236
  const candidate = await prepareRuntimeCandidate(runtimeRoot, staging => remote
161
237
  ? materializeRegistry(plan.source, remote, staging)
162
- : materialize(packageRoot, staging, { registry }));
238
+ : materialize(packageRoot, staging, { registry }), { repair: true, deferExisting: true });
163
239
  candidates.set(key, candidate);
164
240
  const resources = path.join(candidate.identity.package_root, 'resources');
165
241
  candidate.createSkill = await readFile(path.join(resources,'craft-create/SKILL.md'),'utf8');
@@ -168,6 +244,9 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
168
244
  if (candidate.updateSkill !== null && !candidate.updateSkill.includes('<!-- craft-mcp:update:v1 -->')) throw new Error('Craft update Skill has an invalid distribution marker');
169
245
  }
170
246
  const candidate = candidates.get(key);
247
+ if (repair && (candidate.identity.version !== plan.previousRuntime.version || candidate.identity.build_id !== plan.previousRuntime.build_id)) {
248
+ throw new Error('Craft repair requires the original version and build; restore the original source or installation package.');
249
+ }
171
250
  if (candidate.identity.package !== pkg.name || (remote && candidate.identity.version !== remote.version)) throw new Error('Craft channel package does not match the resolved release');
172
251
  const managedUpdateSkill = plan.previousState?.skills?.['craft-update'] === plan.paths.updateSkill;
173
252
  plan.writeUpdateSkill = candidate.updateSkill !== null || managedUpdateSkill;
@@ -186,6 +265,7 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
186
265
  for (const plan of plans) {
187
266
  if (attempt > 0) {
188
267
  const original = initialPlans.find(initial => initial.host === plan.host);
268
+ if (repair && !sameRuntimeIdentity(original.previousRuntime, plan.previousRuntime)) throw new Error('The selected Craft target changed during repair; run doctor again.');
189
269
  const before = original.previousState?.source ?? original.legacySource ?? original.source;
190
270
  const after = plan.previousState?.source ?? plan.legacySource;
191
271
  if (after?.channel && (after.channel !== before.channel || (before.registry && before.registry !== after.registry))) {
@@ -197,20 +277,31 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
197
277
  checkInstallVersion(candidate.identity, plan, plan.integrity);
198
278
  const old = craftConfig(plan.configInput, plan.host, plan.previousName);
199
279
  const connection = { ...old, command: process.execPath, args: [candidate.identity.entry, '--workspace', plan.workspace],
200
- env: { ...old?.env, ...hostRuntimeEnvironment(plan.host,old?.env), CRAFT_CLIENT_IDE: plan.host, CRAFT_WEB_URL: plan.platform, CLIENT_WORKSPACE_ROOT: plan.workspace,
280
+ env: { ...old?.env, ...hostRuntimeEnvironment(plan.host,old?.env), CRAFT_CLIENT_IDE: plan.host, CRAFT_SERVER_ID: instance, CRAFT_WEB_URL: plan.platform, CLIENT_WORKSPACE_ROOT: plan.workspace,
201
281
  CRAFT_INSTALLATION_FILE: plan.statePath.file, CRAFT_RUNTIME_REVISION: candidate.identity.build_id }, ...hostConnectionOptions(plan.host) };
202
- const expected = { version: candidate.identity.version, build_id: candidate.identity.build_id, host: plan.host, workspace: plan.workspace, platform: plan.platform };
282
+ const expected = { version: candidate.identity.version, build_id: candidate.identity.build_id, host: plan.host, serverId: instance, workspace: plan.workspace, platform: plan.platform };
283
+ plan.probeRuntime = async runtime => {
284
+ const verified = await probe({ ...connection, args: [runtime.entry, '--workspace', plan.workspace] }, expected);
285
+ if (verified.runtime?.activation_mode !== activationMode) throw new Error('Craft runtime requires a legacy frontend; install a next_mcp_start distribution');
286
+ return verified;
287
+ };
203
288
  const key = JSON.stringify({ connection, expected });
204
- const verified = verifiedCache.get(key) ?? await probe(connection, expected);
205
- if (verified.runtime?.activation_mode !== activationMode) throw new Error('Craft runtime requires a legacy frontend; install a next_mcp_start distribution');
289
+ const verified = verifiedCache.get(key) ?? await plan.probeRuntime(candidate.identity);
206
290
  verifiedCache.set(key, verified);
207
291
  verifiedByHost.set(plan.host, verified);
208
292
  }
209
293
  for (const candidate of new Set(plans.map(plan => plan.candidate))) {
210
294
  if (!sameRuntimeIdentity(await getRuntimeIdentity(candidate.identity.package_root), candidate.identity)) throw new Error('Craft candidate changed during verification; installation refused');
211
- await refreshRuntimeCandidate(candidate);
295
+ const verifiedExisting = await refreshRuntimeCandidate(candidate, async runtime => {
296
+ const results = new Map();
297
+ for (const plan of plans) {
298
+ if (plan.candidate === candidate) results.set(plan.host, await plan.probeRuntime(runtime));
299
+ }
300
+ return results;
301
+ });
302
+ if (verifiedExisting) for (const [host, result] of verifiedExisting) verifiedByHost.set(host, result);
212
303
  }
213
- const lockPaths = [...new Set(plans.flatMap(plan => [plan.statePath.file, craftConfig(plan.configInput, plan.host, plan.previousName)?.env?.CRAFT_INSTALLATION_FILE].filter(Boolean)).map(file => path.resolve(file)))].sort();
304
+ const lockPaths = [...new Set(plans.flatMap(plan => [plan.paths.config, plan.statePath.file, craftConfig(plan.configInput, plan.host, plan.previousName)?.env?.CRAFT_INSTALLATION_FILE].filter(Boolean)).map(file => path.resolve(file)))].sort();
214
305
  for (const file of lockPaths) {
215
306
  await assertPlainPath(file); await mkdir(path.dirname(file), { recursive: true });
216
307
  stateLocks.push(await lockfile.lock(file, { realpath: false, stale: 120000, retries: 0 }));
@@ -232,14 +323,15 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
232
323
  const origin = plan.integrity ? { kind:'npm', registry:source.registry, integrity:plan.integrity }
233
324
  : identity.build_id === plan.previousRuntime?.build_id && plan.previousRuntime.origin?.registry === source.registry ? plan.previousRuntime.origin : undefined;
234
325
  const target = origin ? { ...identity, origin } : identity;
235
- const { createSkill: desiredSkill, updateSkill: desiredUpdateSkill } = candidate;
326
+ const desiredSkill = renderInstanceSkill(candidate.createSkill, 'craft-create', instance);
327
+ const desiredUpdateSkill = candidate.updateSkill === null ? null : renderInstanceSkill(candidate.updateSkill, 'craft-update', instance);
236
328
  const migration = plan.previousState?.migration ?? (plan.legacySource ? { from_server: plan.previousName, ...plan.legacySource } : undefined);
237
329
  const launcherPlan = await planLauncher(plan.statePath.file, plan.previousState?.launcher, identity.package_root);
238
330
  const loginDir = plan.host === 'workbuddy' && process.platform === 'win32'
239
331
  ? craftConfig(plan.configInput, plan.host, plan.previousName)?.env?.CLIENT_DATA_DIR || process.env.CLIENT_DATA_DIR || defaultProfileDataDir(plan.workspace, plan.platform)
240
332
  : undefined;
241
333
  if (loginDir && !path.isAbsolute(loginDir)) throw new Error('WorkBuddy CLIENT_DATA_DIR must be absolute');
242
- const state = { schema: 2, activation_mode: activationMode, id: plan.statePath.id, host: plan.host, server_id: 'craft', config: plan.paths.config,
334
+ const state = { schema: 2, activation_mode: activationMode, id: plan.statePath.id, host: plan.host, server_id: instance, config: plan.paths.config,
243
335
  launcher: launcherPlan.launcher,
244
336
  ...(loginDir ? {login_data_dir: path.resolve(loginDir)} : {}),
245
337
  workspace: plan.workspace, platform: plan.platform, runtime_root: runtimeRoot, source,
@@ -254,13 +346,13 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
254
346
  const same = priorComparable && JSON.stringify(priorComparable) === JSON.stringify(state);
255
347
  const desiredState = same ? plan.previousState : { ...state, updated_at: new Date().toISOString() };
256
348
  const connection = { command: process.execPath, args: [launcherPlan.launcher.entry, '--workspace', plan.workspace],
257
- env: { ...hostRuntimeEnvironment(plan.host,craftConfig(plan.configInput,plan.host,plan.previousName)?.env), CRAFT_CLIENT_IDE: plan.host, CRAFT_WEB_URL: plan.platform, CLIENT_WORKSPACE_ROOT: plan.workspace, CRAFT_INSTALLATION_FILE: plan.statePath.file, CRAFT_RUNTIME_REVISION: identity.build_id },
349
+ env: { ...hostRuntimeEnvironment(plan.host,craftConfig(plan.configInput,plan.host,plan.previousName)?.env), CRAFT_CLIENT_IDE: plan.host, CRAFT_SERVER_ID: instance, CRAFT_WEB_URL: plan.platform, CLIENT_WORKSPACE_ROOT: plan.workspace, CRAFT_INSTALLATION_FILE: plan.statePath.file, CRAFT_RUNTIME_REVISION: identity.build_id },
258
350
  ...hostConnectionOptions(plan.host) };
259
351
  const configured = craftConfig(plan.configInput, plan.host, plan.previousName);
260
352
  // Some hosts omit an enabled flag when saving their configuration. Do not
261
353
  // reinsert defaults into an already enabled registration.
262
354
  const alreadyEnabled = configured && configured.disabled !== true && configured.enabled !== false && configured.enable !== false;
263
- const updated = mergeConfig(plan.configInput, plan.host, connection, { previousName: plan.previousName, enable: !alreadyEnabled });
355
+ const updated = mergeConfig(plan.configInput, plan.host, connection, { serverId: instance, previousName: plan.previousName, enable: !alreadyEnabled });
264
356
  const verified = verifiedByHost.get(plan.host);
265
357
  changes.push({ file: plan.paths.skill, before: plan.existingSkill, after: desiredSkill });
266
358
  if (plan.writeUpdateSkill) changes.push({ file: plan.paths.updateSkill, before: plan.existingUpdateSkill, after: desiredUpdateSkill });
@@ -268,9 +360,9 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
268
360
  // managed entrypoints available before exposing the new launch command.
269
361
  changes.push(launcherPlan.change, { file: plan.statePath.file, before: plan.stateBefore, after: same ? plan.stateBefore : JSON.stringify(desiredState, null, 2) + '\n' },
270
362
  { file: plan.paths.config, before: plan.original, after: updated });
271
- results.push({ host: plan.host, ...plan.paths, installation: plan.statePath.file, launcher: state.launcher, source, policy: state.policy, ...(migration ? { migration } : {}), ...(plan.previousName !== 'craft' ? { migrated_from: plan.previousName } : {}), ...(plan.fallbackSnapshot ? { imported_from: plan.fallbackSnapshot.file } : {}), verified,
363
+ results.push({ host: plan.host, server_id: instance, ...plan.paths, installation: plan.statePath.file, launcher: state.launcher, source, policy: state.policy, ...(migration ? { migration } : {}), ...(plan.previousName !== instance ? { migrated_from: plan.previousName } : {}), ...(plan.fallbackSnapshot ? { imported_from: plan.fallbackSnapshot.file } : {}), verified,
272
364
  activation_mode: activationMode, reconnect_required: true, activation: { status: 'pending_connection_verification', expected: identity },
273
- connection_handoff: connectionHandoff({host:plan.host,target:identity,workspace:plan.workspace,platform:plan.platform,intent:'install'}) });
365
+ connection_handoff: connectionHandoff({host:plan.host,serverId:instance,channel:source.channel,target:identity,workspace:plan.workspace,platform:plan.platform,intent:'install'}) });
274
366
  }
275
367
  const written = await commitFiles(changes);
276
368
  return { ...(published.size === 1 ? {runtime:published.values().next().value} : {runtimes:[...published.values()]}), hosts: results, ...written,
@@ -301,13 +393,13 @@ async function verifyInstalledSkills(installation, paths, connection, snapshot)
301
393
  contents.set(name, content);
302
394
  }
303
395
  const candidates = installation ? installation.skills_runtime ? [installation.skills_runtime] : [installation.target, installation.anchor] : [await getRuntimeIdentity(path.resolve(path.dirname(connection.args[0]), '..'))];
396
+ if (installation) await verifyRuntimeProductFiles(installation.target, installation);
304
397
  for (const candidate of candidates) {
305
- const actual = await getRuntimeIdentity(candidate.package_root);
306
- if (actual.package !== candidate.package || actual.version !== candidate.version || actual.build_id !== candidate.build_id) throw new Error('Installed Skill runtime files differ from their recorded identity');
398
+ if (installation && !sameRuntimeIdentity(candidate, installation.target)) await verifyRuntimeProductFiles(candidate, installation);
307
399
  let matches = true;
308
400
  for (const { name, marker } of entries) {
309
401
  const expected = await optionalFile(path.join(candidate.package_root, 'resources', name, 'SKILL.md'));
310
- if (!expected?.includes(marker) || contents.get(name) !== expected) { matches = false; break; }
402
+ if (!expected?.includes(marker) || contents.get(name) !== renderInstanceSkill(expected, name, installation?.server_id ?? 'craft')) { matches = false; break; }
311
403
  }
312
404
  if (matches) return { status: 'verified', runtime: skillRuntimeIdentity(candidate), managed: entries.map(entry => entry.name) };
313
405
  }
@@ -317,18 +409,20 @@ async function verifyInstalledSkills(installation, paths, connection, snapshot)
317
409
  throw new Error('Craft managed Skills differ from the recorded installed Skill runtime; run install again');
318
410
  }
319
411
 
320
- export async function doctorHosts({ ide, home = os.homedir(), codexHome, hostOptions = {}, probe = probeRuntime }) {
412
+ export async function doctorHosts({ ide, home = os.homedir(), codexHome, hostOptions = {}, serverId = 'craft', probe = probeRuntime }) {
413
+ validateServerId(serverId);
321
414
  const results = [];
322
415
  for (const host of installTargets(ide)) {
323
416
  for (let attempt = 0; attempt < 4; attempt++) {
324
417
  try {
325
- const paths = hostPaths(home, host, codexHome, hostOptions);
326
- await assertHostConfigScope(paths.config,host,paths.configPeers);
418
+ const paths = hostPaths(home, host, codexHome, { ...hostOptions, serverId });
419
+ await assertHostConfigScope(paths.config,host,paths.configPeers,serverId);
327
420
  await assertPlainPath(paths.config);
328
- assertDshSharedScope(paths);
421
+ assertDshSharedScope(paths,serverId);
329
422
  const configText = await optionalFile(paths.config) ?? '';
330
- const connection = craftConfig(configText, host);
423
+ const connection = craftConfig(configText, host, serverId);
331
424
  if (!connection?.command || connection.env?.CRAFT_CLIENT_IDE !== host) throw new Error(host + ': Craft installation missing or host marker incorrect; run install --ide ' + host);
425
+ if ((connection.env.CRAFT_SERVER_ID ?? 'craft') !== serverId) throw new Error('Craft instance marker differs from its registration: ' + serverId);
332
426
  if (connection.disabled === true || connection.enabled === false || connection.enable === false) throw new Error(host + ': Craft MCP is disabled');
333
427
  let installation = null, skillsVerification, verificationError;
334
428
  const file = connection.env.CRAFT_INSTALLATION_FILE, skillSnapshots = new Map();
@@ -337,6 +431,7 @@ export async function doctorHosts({ ide, home = os.homedir(), codexHome, hostOpt
337
431
  try {
338
432
  if (await optionalFile(paths.config) !== configText) throw installationChanged();
339
433
  installation = await readInstallation(file);
434
+ checkInstanceBinding(installation, host, paths, serverId, file);
340
435
  const entries = installation.skills ? installedSkillEntries(installation) : [{ file: paths.skill }];
341
436
  for (const entry of entries) {
342
437
  await assertPlainPath(entry.file);
@@ -368,13 +463,13 @@ export async function doctorHosts({ ide, home = os.homedir(), codexHome, hostOpt
368
463
  const skillsPending = Boolean(installation && skillsVerification.runtime?.build_id !== installation.target.build_id);
369
464
  const checkConnection = installation && !installation.launcher ? { ...connection, args: [installation.target.entry, '--workspace', installation.workspace] } : connection;
370
465
  let verified, probeError;
371
- try { verified = await probe(checkConnection, { host, ...(installation ? { version: installation.target.version, build_id: installation.target.build_id, workspace: installation.workspace, platform: installation.platform } : {}) }); }
466
+ try { verified = await probe(checkConnection, { host, serverId, ...(installation ? { version: installation.target.version, build_id: installation.target.build_id, workspace: installation.workspace, platform: installation.platform } : {}) }); }
372
467
  catch (error) { probeError = error; }
373
468
  // The launcher may observe a newer target while a diagnostic probe is
374
469
  // starting. Re-read all scope/config fields on the next bounded attempt.
375
470
  await stableSnapshot();
376
471
  if (probeError) throw probeError;
377
- results.push({ host, ...paths, entry: connection.args[0], target: installation?.target, skills_pending_activation: skillsPending, skills_verification: skillsVerification, verified });
472
+ results.push({ host, server_id: serverId, ...paths, entry: connection.args[0], target: installation?.target, skills_pending_activation: skillsPending, skills_verification: skillsVerification, verified });
378
473
  break;
379
474
  } catch (error) {
380
475
  if (!['ELOCKED', 'INSTALLATION_CHANGED'].includes(error.code) || attempt === 3) throw error;
@@ -394,19 +489,20 @@ export async function installWithLoginTask(options) {
394
489
  if (process.platform === 'win32') {
395
490
  const workbuddy = result.hosts.find(host => host.host === 'workbuddy');
396
491
  if (workbuddy) {
492
+ const instanceOption = workbuddy.server_id === 'craft' ? '' : ' --instance ' + workbuddy.server_id;
397
493
  try {
398
494
  const { ensureWorkBuddyLoginTask } = await import('./workbuddy-login-task.mjs');
399
495
  workbuddy.login_task = await ensureWorkBuddyLoginTask(workbuddy.installation);
400
496
  } catch (error) {
401
497
  workbuddy.login_task = {status: 'unavailable', reason: error.message,
402
- next: 'Windows local-page login requires the on-demand task. Retry install --ide workbuddy after resolving the reported error.'};
498
+ next: 'Windows local-page login requires the on-demand task. Run login-task --setup --ide workbuddy' + instanceOption + ' after resolving the reported error.'};
403
499
  }
404
500
  try {
405
501
  const { ensureWorkBuddyPreviewTask } = await import('./workbuddy-login-task.mjs');
406
502
  workbuddy.preview_task = await ensureWorkBuddyPreviewTask(workbuddy.installation);
407
503
  } catch (error) {
408
504
  workbuddy.preview_task = {status:'unavailable',reason:error.message,
409
- next:'Windows WorkBuddy preview requires the on-demand task. Run preview-task --setup --ide workbuddy after resolving the reported error.'};
505
+ next:'Windows WorkBuddy preview requires the on-demand task. Run preview-task --setup --ide workbuddy' + instanceOption + ' after resolving the reported error.'};
410
506
  }
411
507
  }
412
508
  }
@@ -415,10 +511,14 @@ export async function installWithLoginTask(options) {
415
511
 
416
512
  export async function runIntegrationCommand(args, packageRoot) {
417
513
  const [command, ...rest] = args, options = {};
418
- for (let i = 0; i < rest.length; i += 2) {
514
+ for (let i = 0; i < rest.length; i++) {
515
+ if (command === 'install' && rest[i] === '--repair' && options.repair === undefined) {
516
+ options.repair = true;
517
+ continue;
518
+ }
419
519
  const name = rest[i].replace(/^--/, '');
420
- if (!rest[i].startsWith('--') || !['ide', 'host-config', 'trae-region', ...(command === 'install' ? ['workspace', 'platform', 'registry', 'channel', 'updates'] : [])].includes(name) || !rest[i + 1] || Object.hasOwn(options, name)) throw new Error('Invalid or repeated option. Use craft-mcp --help.');
421
- options[name] = rest[i + 1];
520
+ if (!rest[i].startsWith('--') || !['ide', 'instance', 'host-config', 'trae-region', ...(command === 'install' ? ['workspace', 'platform', 'registry', 'channel', 'updates'] : [])].includes(name) || !rest[i + 1] || Object.hasOwn(options, name)) throw new Error('Invalid or repeated option. Use craft-mcp --help.');
521
+ options[name] = rest[++i];
422
522
  }
423
523
  options.codexHome = process.env.CODEX_HOME;
424
524
  options.hostOptions = hostCommandOptions(options);
@@ -426,8 +526,12 @@ export async function runIntegrationCommand(args, packageRoot) {
426
526
  const { name } = JSON.parse(await readFile(path.join(packageRoot,'package.json'),'utf8'));
427
527
  const request = await npmInstallSelector(packageRoot, name);
428
528
  options.selector = request?.kind ?? 'management';
429
- options.channel ??= request?.tag;
529
+ if (options.repair) options.instance ??= serverIdForChannel(request?.tag === 'latest' ? 'stable' : request?.tag);
530
+ else options.channel ??= request?.tag;
531
+ if (options.channel === 'latest') options.channel = 'stable';
430
532
  }
533
+ options.serverId = validateServerId(options.instance ?? serverIdForChannel(options.channel));
534
+ if (command === 'install' && options.serverId === 'craft' && options.channel && options.channel !== 'stable') throw new Error('The craft instance tracks stable; select a named test instance for ' + options.channel);
431
535
  const result = command === 'install' ? await installWithLoginTask({ ...options, packageRoot }) : await doctorHosts(options);
432
536
  process.stdout.write(JSON.stringify(result, null, 2) + '\n');
433
537
  }
@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';
3
3
  import { optionalFile } from './files.mjs';
4
4
  import { parseVersion, requireForwardVersion } from './version-policy.mjs';
5
5
  import { hosts } from './hosts.mjs';
6
+ import { instanceSkillName } from './instance-skill.mjs';
6
7
 
7
8
  export const defaultRegistry = 'https://registry.npmjs.org/';
8
9
  export const activationMode = 'next_mcp_start';
@@ -15,7 +16,7 @@ export function installedSkillEntries(state) {
15
16
  if (state.skills === undefined) return [];
16
17
  if (!state.skills || typeof state.skills !== 'object' || Array.isArray(state.skills) || !state.skills['craft-create']) throw new Error('Invalid installed Skill destinations');
17
18
  return Object.entries(state.skills).map(([name, file]) => {
18
- if (!Object.hasOwn(managedSkillMarkers, name) || typeof file !== 'string' || !path.isAbsolute(file) || path.basename(file) !== 'SKILL.md' || path.basename(path.dirname(file)) !== name) throw new Error('Invalid installed Skill destination');
19
+ if (!Object.hasOwn(managedSkillMarkers, name) || typeof file !== 'string' || !path.isAbsolute(file) || path.basename(file) !== 'SKILL.md' || path.basename(path.dirname(file)) !== instanceSkillName(name, state.server_id)) throw new Error('Invalid installed Skill destination');
19
20
  return { name, file, marker: managedSkillMarkers[name] };
20
21
  });
21
22
  }