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

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 (113) hide show
  1. package/README.md +2 -2
  2. package/bin/craft-mcp.mjs +11 -2
  3. package/dist-server/core/http-utils.mjs +11 -0
  4. package/dist-server/game-workflow/asset-formats.mjs +1 -1
  5. package/dist-server/game-workflow/bundle-files.mjs +19 -0
  6. package/dist-server/game-workflow/bundle-template.mjs +5 -0
  7. package/dist-server/game-workflow/context-state.mjs +1 -1
  8. package/dist-server/game-workflow/draft-archive.mjs +61 -0
  9. package/dist-server/game-workflow/draft-binding-migration.mjs +73 -0
  10. package/dist-server/game-workflow/draft-uploads.mjs +258 -75
  11. package/dist-server/game-workflow/native-context.mjs +4 -1
  12. package/dist-server/game-workflow/project-bundles.mjs +17 -6
  13. package/dist-server/game-workflow/projects.mjs +4 -0
  14. package/dist-server/game-workflow/template-refresh.mjs +430 -0
  15. package/dist-server/integrations/distribution-targets.mjs +2 -0
  16. package/dist-server/integrations/files.mjs +30 -2
  17. package/dist-server/integrations/fixed-launcher.mjs +4 -4
  18. package/dist-server/integrations/install.mjs +5 -5
  19. package/dist-server/integrations/installation-state.mjs +6 -7
  20. package/dist-server/integrations/launcher-start.mjs +12 -8
  21. package/dist-server/integrations/opencode-config.mjs +1 -1
  22. package/dist-server/integrations/project-setup.mjs +0 -1
  23. package/dist-server/integrations/runtime-candidate.mjs +8 -12
  24. package/dist-server/integrations/runtime-gc.mjs +20 -21
  25. package/dist-server/integrations/runtime.mjs +7 -3
  26. package/dist-server/integrations/updates.mjs +64 -27
  27. package/dist-server/launcher.mjs +39 -14
  28. package/dist-server/mcp/login-page.mjs +2 -2
  29. package/dist-server/mcp/server.mjs +10 -12
  30. package/dist-server/mcp/update-session.mjs +3 -3
  31. package/dist-server/upstream/{craft-aigc.mjs → craft-platform.mjs} +40 -115
  32. package/dist-server/upstream/draft-audit.mjs +51 -0
  33. package/dist-server/upstream/draft-transport.mjs +184 -0
  34. package/package.json +3 -3
  35. package/resources/craft-update/SKILL.md +2 -0
  36. package/resources/targets/claude/js/js/bundle.json +15 -9
  37. package/resources/targets/claude/js/target.json +8 -6
  38. package/resources/targets/claude/js3d/js3d/bundle.json +21 -10
  39. package/resources/targets/claude/js3d/target.json +14 -7
  40. package/resources/targets/codebuddy/js/js/bundle.json +15 -9
  41. package/resources/targets/codebuddy/js/target.json +8 -6
  42. package/resources/targets/codebuddy/js3d/js3d/bundle.json +21 -10
  43. package/resources/targets/codebuddy/js3d/target.json +14 -7
  44. package/resources/targets/codex/js/js/bundle.json +15 -9
  45. package/resources/targets/codex/js/target.json +8 -6
  46. package/resources/targets/codex/js3d/js3d/bundle.json +21 -10
  47. package/resources/targets/codex/js3d/target.json +14 -7
  48. package/resources/targets/comate/js/js/bundle.json +15 -9
  49. package/resources/targets/comate/js/target.json +8 -6
  50. package/resources/targets/comate/js3d/js3d/bundle.json +21 -10
  51. package/resources/targets/comate/js3d/target.json +14 -7
  52. package/resources/targets/cursor/js/js/bundle.json +15 -9
  53. package/resources/targets/cursor/js/target.json +8 -6
  54. package/resources/targets/cursor/js3d/js3d/bundle.json +21 -10
  55. package/resources/targets/cursor/js3d/target.json +14 -7
  56. package/resources/targets/dsh/js/js/bundle.json +15 -9
  57. package/resources/targets/dsh/js/target.json +8 -6
  58. package/resources/targets/dsh/js3d/js3d/bundle.json +21 -10
  59. package/resources/targets/dsh/js3d/target.json +14 -7
  60. package/resources/targets/index.json +56 -56
  61. package/resources/targets/kimi/js/js/bundle.json +15 -9
  62. package/resources/targets/kimi/js/target.json +8 -6
  63. package/resources/targets/kimi/js3d/js3d/bundle.json +21 -10
  64. package/resources/targets/kimi/js3d/target.json +14 -7
  65. package/resources/targets/opencode/js/js/bundle.json +15 -9
  66. package/resources/targets/opencode/js/target.json +8 -6
  67. package/resources/targets/opencode/js3d/js3d/bundle.json +21 -10
  68. package/resources/targets/opencode/js3d/target.json +14 -7
  69. package/resources/targets/qoder/js/js/bundle.json +15 -9
  70. package/resources/targets/qoder/js/target.json +8 -6
  71. package/resources/targets/qoder/js3d/js3d/bundle.json +21 -10
  72. package/resources/targets/qoder/js3d/target.json +14 -7
  73. package/resources/targets/qoder-cn/js/js/bundle.json +15 -9
  74. package/resources/targets/qoder-cn/js/target.json +8 -6
  75. package/resources/targets/qoder-cn/js3d/js3d/bundle.json +21 -10
  76. package/resources/targets/qoder-cn/js3d/target.json +14 -7
  77. package/resources/targets/qwen/js/js/bundle.json +15 -9
  78. package/resources/targets/qwen/js/target.json +8 -6
  79. package/resources/targets/qwen/js3d/js3d/bundle.json +21 -10
  80. package/resources/targets/qwen/js3d/target.json +14 -7
  81. package/resources/targets/trae/js/js/bundle.json +15 -9
  82. package/resources/targets/trae/js/target.json +8 -6
  83. package/resources/targets/trae/js3d/js3d/bundle.json +21 -10
  84. package/resources/targets/trae/js3d/target.json +14 -7
  85. package/resources/targets/workbuddy/js/js/bundle.json +15 -9
  86. package/resources/targets/workbuddy/js/target.json +8 -6
  87. package/resources/targets/workbuddy/js3d/js3d/bundle.json +21 -10
  88. package/resources/targets/workbuddy/js3d/target.json +14 -7
  89. package/resources/targets/zcode/js/js/bundle.json +15 -9
  90. package/resources/targets/zcode/js/target.json +8 -6
  91. package/resources/targets/zcode/js3d/js3d/bundle.json +21 -10
  92. package/resources/targets/zcode/js3d/target.json +14 -7
  93. package/resources/templates/js/materialize_paths.json +9 -0
  94. package/resources/templates/js/project/package.json +1 -0
  95. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform-capture-dom.mjs +176 -0
  96. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform.d.mts +5 -1
  97. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform.mjs +87 -3
  98. package/resources/templates/js/project/runtime/lightgame/1.1.0/release.json +3 -2
  99. package/resources/templates/js/project/scripts/refresh-runtime.mjs +50 -0
  100. package/resources/templates/js3d/materialize_paths.json +9 -0
  101. package/resources/templates/js3d/project/package.json +4 -2
  102. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform-capture-dom.mjs +176 -0
  103. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform.d.mts +5 -1
  104. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform.mjs +87 -3
  105. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/release.json +3 -2
  106. package/resources/templates/js3d/project/scripts/refresh-runtime.mjs +50 -0
  107. package/resources/templates/js3d/project/scripts/skill-modules/gameplay-check/check.mjs +331 -0
  108. package/resources/templates/js3d/project/src/game/capability/core.ts +3 -0
  109. package/resources/templates/js3d/project/src/main.ts +23 -6
  110. package/resources/templates/js3d/project/src/skill-modules/gameplay/core/index.d.mts +92 -0
  111. package/resources/templates/js3d/project/src/skill-modules/gameplay/core/index.mjs +375 -0
  112. package/resources/templates/js3d/project/src/skill-modules/gameplay/installed.json +6 -0
  113. package/dist-server/game-workflow/local-context.mjs +0 -64
@@ -0,0 +1,430 @@
1
+ import path from 'node:path';
2
+ import { chmod, lstat, open, readdir, readFile, realpath, rename, rm, rmdir } from 'node:fs/promises';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { safeProjectFile } from './asset-import.mjs';
5
+
6
+ const digest = value => createHash('sha256').update(value).digest('hex');
7
+
8
+ export const materializePathsFile = 'materialize_paths.json';
9
+
10
+ // Never let template refresh overwrite user gameplay code, configs, progress,
11
+ // runtime/dependency contracts, or Craft/host metadata directories.
12
+ const FORBIDDEN_ROOTS = new Set([
13
+ 'SPEC', 'src', 'Content', 'configs',
14
+ 'unified_data_control_config.json', 'AGENTS.md', 'package.json', 'game-runtime.json',
15
+ '.git', '.craft', '.agents', '.cursor', '.claude', '.workbuddy', '.codebuddy',
16
+ '.dsh', '.zcode', '.kimi-code', '.trae', '.qoder', '.qoder-cn', '.comate', '.opencode', '.qwen',
17
+ 'node_modules',
18
+ ]);
19
+
20
+ function validateRelativeSegments(entry, raw) {
21
+ if (typeof entry !== 'string' || !entry || entry.includes('\\') || entry.includes('\0') || /[:*?<>"|]/.test(entry)) {
22
+ throw new Error('Invalid template refresh path: ' + raw);
23
+ }
24
+ const segments = entry.split('/');
25
+ if (FORBIDDEN_ROOTS.has(segments[0]) || segments.some(segment =>
26
+ !segment || segment === '.' || segment === '..' ||
27
+ segment === '.git' || segment === '.craft' || segment === '.claude' ||
28
+ segment === 'node_modules' || segment.startsWith('.env')
29
+ )) {
30
+ throw new Error('Forbidden template refresh path: ' + raw);
31
+ }
32
+ return entry;
33
+ }
34
+
35
+ function collapsePaths(entries) {
36
+ const unique = [...new Set(entries)].sort();
37
+ return unique.filter(entry => !unique.some(parent => parent !== entry && entry.startsWith(parent + '/')));
38
+ }
39
+
40
+ export function normalizeProjectRefreshPaths(value) {
41
+ if (value === undefined) return [];
42
+ if (!Array.isArray(value)) throw new Error('template_refresh_paths must be an array');
43
+ return collapsePaths(value.map(entry => validateRelativeSegments(entry, entry)));
44
+ }
45
+
46
+ function normalizeOmitEntries(value) {
47
+ if (value === undefined) return [];
48
+ if (!Array.isArray(value)) throw new Error('materialize_paths.json omit must be an array');
49
+ return value.map(entry => {
50
+ if (typeof entry !== 'string' || !entry || entry.includes('\\') || entry.includes('\0') || /[:*?<>"|]/.test(entry)) {
51
+ throw new Error('Invalid materialize_paths.json omit path');
52
+ }
53
+ const segments = entry.split('/');
54
+ if (segments.length < 2 || !['.agents', 'project'].includes(segments[0]) || segments.some(s => !s || s === '.' || s === '..')) {
55
+ throw new Error('Invalid materialize_paths.json omit path: ' + entry);
56
+ }
57
+ return entry;
58
+ });
59
+ }
60
+
61
+ export function parseMaterializePaths(raw, expectedEngine) {
62
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
63
+ throw new Error('Invalid materialize_paths.json: expected a JSON object');
64
+ }
65
+ if (expectedEngine && raw.engine !== expectedEngine) {
66
+ throw new Error('materialize_paths.json engine mismatch: expected ' + expectedEngine);
67
+ }
68
+ const omit = normalizeOmitEntries(raw.omit);
69
+ if (raw.refresh !== undefined && !Array.isArray(raw.refresh)) {
70
+ throw new Error('materialize_paths.json refresh must be an array');
71
+ }
72
+ const refresh = [];
73
+ for (const entry of raw.refresh ?? []) {
74
+ if (typeof entry !== 'string' || !entry.startsWith('project/')) {
75
+ throw new Error('materialize_paths.json refresh entry must start with project/: ' + entry);
76
+ }
77
+ if (omit.some(omitted => entry === omitted || entry.startsWith(omitted + '/'))) {
78
+ throw new Error('materialize_paths.json refresh entry conflicts with omit: ' + entry);
79
+ }
80
+ refresh.push(validateRelativeSegments(entry.slice('project/'.length), entry));
81
+ }
82
+ return collapsePaths(refresh);
83
+ }
84
+
85
+ export async function readTemplateRefreshPaths(templateDir, expectedEngine) {
86
+ const file = path.join(path.dirname(templateDir), materializePathsFile);
87
+ let stat;
88
+ try { stat = await lstat(file); }
89
+ catch (error) {
90
+ if (error.code === 'ENOENT') return [];
91
+ throw error;
92
+ }
93
+ if (stat.isSymbolicLink() || !stat.isFile()) {
94
+ throw new Error('materialize_paths.json must be a regular file');
95
+ }
96
+ const raw = JSON.parse(await readFile(file, 'utf8'));
97
+ return parseMaterializePaths(raw, expectedEngine);
98
+ }
99
+
100
+ export function isProjectRefreshPath(relativePath, refreshPaths) {
101
+ return refreshPaths.some(entry => relativePath === entry || relativePath.startsWith(entry + '/'));
102
+ }
103
+
104
+ export function managedTemplateFileHashes(bundle) {
105
+ const refreshPaths = normalizeProjectRefreshPaths(bundle?.template_refresh_paths);
106
+ if (!refreshPaths.length) return {};
107
+ const prefix = bundle.engine + '/project/';
108
+ const result = {};
109
+ for (const [name, hash] of Object.entries(bundle.files ?? {})) {
110
+ if (!name.startsWith(prefix)) continue;
111
+ const relative = name.slice(prefix.length);
112
+ if (isProjectRefreshPath(relative, refreshPaths)) result[relative] = hash;
113
+ }
114
+ return result;
115
+ }
116
+
117
+ async function statOptional(file) {
118
+ try { return await lstat(file); }
119
+ catch (error) {
120
+ if (error.code === 'ENOENT') return null;
121
+ throw error;
122
+ }
123
+ }
124
+
125
+ async function resolveSafeProjectEntry(project, relative) {
126
+ const root = await realpath(project);
127
+ if (root !== project) throw new Error('Project path changed');
128
+ const pieces = relative.split('/');
129
+ if (pieces.some(p => !p || p === '.' || p === '..' || p.includes('\\'))) {
130
+ throw new Error('Invalid project-relative path: ' + relative);
131
+ }
132
+ let current = root;
133
+ for (let i = 0; i < pieces.length; i++) {
134
+ current = path.join(current, pieces[i]);
135
+ const stat = await statOptional(current);
136
+ if (!stat) return { target: path.join(root, ...pieces), stat: null };
137
+ if (stat.isSymbolicLink()) {
138
+ throw new Error('Managed template path contains a symbolic link: ' + relative);
139
+ }
140
+ if (i < pieces.length - 1) {
141
+ if (!stat.isDirectory()) {
142
+ return { target: path.join(root, ...pieces), stat: null, blockedByFile: pieces.slice(0, i + 1).join('/') };
143
+ }
144
+ } else {
145
+ if (!stat.isFile() && !stat.isDirectory()) {
146
+ throw new Error('Managed template path contains an unsupported entry: ' + relative);
147
+ }
148
+ return { target: current, stat };
149
+ }
150
+ }
151
+ return { target: current, stat: null };
152
+ }
153
+
154
+ async function scanSubtree(rootDir, baseRelative) {
155
+ const files = {};
156
+ const dirs = [];
157
+ async function walk(currentDir, relative) {
158
+ const entries = (await readdir(currentDir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
159
+ for (const entry of entries) {
160
+ const full = path.join(currentDir, entry.name);
161
+ const childRelative = relative + '/' + entry.name;
162
+ if (entry.isSymbolicLink()) throw new Error('Managed template path contains a symbolic link: ' + childRelative);
163
+ if (entry.isDirectory()) {
164
+ dirs.push(childRelative);
165
+ await walk(full, childRelative);
166
+ } else if (entry.isFile()) {
167
+ files[childRelative] = digest(await readFile(full));
168
+ } else {
169
+ throw new Error('Managed template path contains an unsupported entry: ' + childRelative);
170
+ }
171
+ }
172
+ }
173
+ await walk(rootDir, baseRelative);
174
+ return { files, dirs };
175
+ }
176
+
177
+ export async function inspectManagedTemplatePaths(project, bundle) {
178
+ const refreshPaths = normalizeProjectRefreshPaths(bundle?.template_refresh_paths);
179
+ if (!refreshPaths.length) return { status: 'valid', paths: [] };
180
+ const expected = managedTemplateFileHashes(bundle);
181
+ for (const entry of refreshPaths) {
182
+ const { target, stat, blockedByFile } = await resolveSafeProjectEntry(project, entry);
183
+ if (blockedByFile) return { status: 'modified', reason: blockedByFile, paths: refreshPaths };
184
+ const isFileEntry = Object.hasOwn(expected, entry);
185
+ if (isFileEntry) {
186
+ if (!stat) return { status: 'modified', reason: entry, paths: refreshPaths };
187
+ if (!stat.isFile()) return { status: 'modified', reason: entry, paths: refreshPaths };
188
+ if (digest(await readFile(target)) !== expected[entry]) {
189
+ return { status: 'modified', reason: entry, paths: refreshPaths };
190
+ }
191
+ continue;
192
+ }
193
+ const prefix = entry + '/';
194
+ const expectedSubtree = Object.fromEntries(
195
+ Object.entries(expected).filter(([name]) => name.startsWith(prefix)).sort(([a], [b]) => a.localeCompare(b))
196
+ );
197
+ if (!Object.keys(expectedSubtree).length) continue;
198
+ if (!stat) return { status: 'modified', reason: entry, paths: refreshPaths };
199
+ if (!stat.isDirectory()) return { status: 'modified', reason: entry, paths: refreshPaths };
200
+ const { files: actual, dirs } = await scanSubtree(target, entry);
201
+ const allNames = new Set([...Object.keys(expectedSubtree), ...Object.keys(actual)]);
202
+ for (const name of [...allNames].sort()) {
203
+ if (actual[name] !== expectedSubtree[name]) {
204
+ return { status: 'modified', reason: name, paths: refreshPaths };
205
+ }
206
+ }
207
+ for (const dir of dirs) {
208
+ if (!Object.keys(expectedSubtree).some(name => name.startsWith(dir + '/'))) {
209
+ return { status: 'modified', reason: dir, paths: refreshPaths };
210
+ }
211
+ }
212
+ }
213
+ return { status: 'valid', paths: refreshPaths };
214
+ }
215
+
216
+ async function ensureWritableDir(dir) {
217
+ const stat = await statOptional(dir);
218
+ if (stat?.isDirectory() && !stat.isSymbolicLink() && (stat.mode & 0o200) === 0) {
219
+ await chmod(dir, stat.mode | 0o700);
220
+ }
221
+ }
222
+
223
+ async function ensureWritableParents(project, relative) {
224
+ const parts = relative.split('/').slice(0, -1);
225
+ let current = project;
226
+ for (const part of parts) {
227
+ current = path.join(current, part);
228
+ await ensureWritableDir(current);
229
+ }
230
+ }
231
+
232
+ async function ensureWritableTree(target) {
233
+ const stat = await statOptional(target);
234
+ if (!stat || stat.isSymbolicLink()) return;
235
+ if (stat.isDirectory()) {
236
+ if ((stat.mode & 0o700) !== 0o700) await chmod(target, stat.mode | 0o700);
237
+ for (const name of await readdir(target)) {
238
+ await ensureWritableTree(path.join(target, name));
239
+ }
240
+ } else if (stat.isFile() && (stat.mode & 0o200) === 0) {
241
+ await chmod(target, stat.mode | 0o600);
242
+ }
243
+ }
244
+
245
+ async function writeAtomicFile(destination, bytes, token, guard) {
246
+ const temporary = destination + '.craft-' + token + '.tmp';
247
+ const handle = await open(temporary, 'wx');
248
+ try {
249
+ await handle.writeFile(bytes);
250
+ await handle.sync();
251
+ } catch (error) {
252
+ await handle.close();
253
+ await rm(temporary, { force: true });
254
+ throw error;
255
+ }
256
+ await handle.close();
257
+ try {
258
+ await guard();
259
+ const existing = await statOptional(destination);
260
+ if (existing?.isFile() && (existing.mode & 0o200) === 0) {
261
+ await chmod(destination, existing.mode | 0o600);
262
+ }
263
+ await rename(temporary, destination);
264
+ } finally {
265
+ await rm(temporary, { force: true });
266
+ }
267
+ }
268
+
269
+ export async function syncManagedTemplateFiles(project, current, guard = async () => {}) {
270
+ const refreshPaths = normalizeProjectRefreshPaths(current?.bundle?.template_refresh_paths);
271
+ if (!refreshPaths.length) {
272
+ return { updated: false, paths: [], updated_files: [], removed_files: [], backup: null };
273
+ }
274
+ if (!current.template) {
275
+ throw new Error('Template source is unavailable for managed template synchronization');
276
+ }
277
+ const expected = managedTemplateFileHashes(current.bundle);
278
+ const actualFiles = {};
279
+ const existingDirs = new Map();
280
+ const typeConflicts = new Set();
281
+
282
+ for (const entry of refreshPaths) {
283
+ const { target, stat, blockedByFile } = await resolveSafeProjectEntry(project, entry);
284
+ if (blockedByFile) {
285
+ throw new Error('Managed template parent path is a file instead of a directory: ' + blockedByFile);
286
+ }
287
+ const isFileEntry = Object.hasOwn(expected, entry);
288
+ if (!stat) continue;
289
+ if (isFileEntry) {
290
+ if (stat.isFile()) {
291
+ actualFiles[entry] = digest(await readFile(target));
292
+ } else if (stat.isDirectory()) {
293
+ typeConflicts.add(entry);
294
+ const { files } = await scanSubtree(target, entry);
295
+ Object.assign(actualFiles, files);
296
+ }
297
+ continue;
298
+ }
299
+ if (stat.isDirectory()) {
300
+ const { files, dirs } = await scanSubtree(target, entry);
301
+ Object.assign(actualFiles, files);
302
+ existingDirs.set(entry, dirs);
303
+ } else if (stat.isFile()) {
304
+ typeConflicts.add(entry);
305
+ actualFiles[entry] = digest(await readFile(target));
306
+ }
307
+ }
308
+
309
+ const toWrite = Object.keys(expected)
310
+ .filter(name => typeConflicts.has(name) || actualFiles[name] !== expected[name])
311
+ .sort();
312
+ const toRemove = Object.keys(actualFiles)
313
+ .filter(name => !Object.hasOwn(expected, name))
314
+ .sort();
315
+ const staleDirs = [...existingDirs.values()].flat()
316
+ .filter(dir => !Object.keys(expected).some(name => name.startsWith(dir + '/')));
317
+
318
+ if (!toWrite.length && !toRemove.length && !typeConflicts.size && !staleDirs.length) {
319
+ return { updated: false, paths: refreshPaths, updated_files: [], removed_files: [], backup: null };
320
+ }
321
+
322
+ // Verify every template source file against the bundle digest before mutating the project.
323
+ const payload = new Map();
324
+ for (const name of toWrite) {
325
+ const sourceFile = path.join(current.template, ...name.split('/'));
326
+ const stat = await lstat(sourceFile);
327
+ if (stat.isSymbolicLink() || !stat.isFile()) {
328
+ throw new Error('Template source is not a regular file: ' + name);
329
+ }
330
+ const bytes = await readFile(sourceFile);
331
+ if (digest(bytes) !== expected[name]) {
332
+ throw new Error('Template source integrity check failed: ' + name);
333
+ }
334
+ payload.set(name, bytes);
335
+ }
336
+
337
+ // Back up every overwritten or removed file before changing the project tree.
338
+ const token = randomUUID();
339
+ const filesToBackup = [...new Set([
340
+ ...toWrite.filter(name => Object.hasOwn(actualFiles, name)),
341
+ ...toRemove,
342
+ ])].sort();
343
+ let backupRoot = null;
344
+ if (filesToBackup.length) {
345
+ backupRoot = '.craft/context-backups/template/' + token;
346
+ for (const name of filesToBackup) {
347
+ await guard();
348
+ const source = await safeProjectFile(project, name);
349
+ const originalBytes = await readFile(source);
350
+ if (digest(originalBytes) !== actualFiles[name]) {
351
+ throw new Error('Project file changed during managed template backup: ' + name);
352
+ }
353
+ const backupDestination = await safeProjectFile(project, backupRoot + '/' + name, true);
354
+ await writeAtomicFile(backupDestination, originalBytes, token, guard);
355
+ if (digest(await readFile(backupDestination)) !== actualFiles[name]) {
356
+ throw new Error('Managed template backup integrity failed: ' + name);
357
+ }
358
+ }
359
+ }
360
+
361
+ // Clear any file-vs-directory type conflicts at managed roots after backup.
362
+ for (const conflict of typeConflicts) {
363
+ await guard();
364
+ await ensureWritableParents(project, conflict);
365
+ const { target } = await resolveSafeProjectEntry(project, conflict);
366
+ await ensureWritableTree(target);
367
+ await rm(target, { recursive: true, force: true });
368
+ }
369
+
370
+ // Ensure existing managed directories are writable (e.g. projects migrated from read-only Web sandboxes).
371
+ for (const entry of refreshPaths) {
372
+ const { target } = await resolveSafeProjectEntry(project, entry);
373
+ await ensureWritableParents(project, entry);
374
+ await ensureWritableTree(target);
375
+ }
376
+
377
+ // Remove retired files inside managed subtrees before writing, so file-to-dir
378
+ // transitions (e.g. a stray file blocking a new directory) resolve cleanly.
379
+ for (const name of toRemove) {
380
+ if (typeConflicts.has(name)) continue;
381
+ await guard();
382
+ const { target: destination, stat: existing } = await resolveSafeProjectEntry(project, name);
383
+ if (!existing) continue;
384
+ if (existing.isFile() && (existing.mode & 0o200) === 0) {
385
+ await chmod(destination, existing.mode | 0o600);
386
+ }
387
+ await rm(destination, { force: true });
388
+ }
389
+
390
+ // Write updated and missing managed template files with normal writable permissions.
391
+ for (const name of toWrite) {
392
+ await guard();
393
+ await ensureWritableParents(project, name);
394
+ const { target: preExistingTarget, stat: preExisting } = await resolveSafeProjectEntry(project, name);
395
+ if (preExisting?.isDirectory()) {
396
+ await ensureWritableTree(preExistingTarget);
397
+ await rm(preExistingTarget, { recursive: true, force: true });
398
+ }
399
+ const destination = await safeProjectFile(project, name, true);
400
+ await writeAtomicFile(destination, payload.get(name), token, guard);
401
+ }
402
+
403
+ // Prune empty obsolete subdirectories inside managed subtrees (deepest first).
404
+ for (const [entry, dirs] of existingDirs) {
405
+ const sorted = [...dirs].sort((a, b) => b.split('/').length - a.split('/').length || b.localeCompare(a));
406
+ for (const dir of sorted) {
407
+ const hasExpectedChild = Object.keys(expected).some(name => name.startsWith(dir + '/'));
408
+ if (hasExpectedChild) continue;
409
+ const { target: full, stat: existing } = await resolveSafeProjectEntry(project, dir);
410
+ if (existing?.isDirectory()) {
411
+ try { await rmdir(full); }
412
+ catch (error) { if (!['ENOTEMPTY', 'ENOENT'].includes(error.code)) throw error; }
413
+ }
414
+ }
415
+ void entry;
416
+ }
417
+
418
+ const verified = await inspectManagedTemplatePaths(project, current.bundle);
419
+ if (verified.status !== 'valid') {
420
+ throw new Error('Managed template synchronization integrity failed: ' + (verified.reason ?? 'unknown'));
421
+ }
422
+
423
+ return {
424
+ updated: true,
425
+ paths: refreshPaths,
426
+ updated_files: toWrite,
427
+ removed_files: toRemove,
428
+ backup: backupRoot ? path.join(project, backupRoot) : null,
429
+ };
430
+ }
@@ -3,6 +3,8 @@ export const distributionTargets = Object.freeze({
3
3
  internal: Object.freeze({ package: '@tencent/craft-mcp', registry: 'https://mirrors.tencent.com/npm/' }),
4
4
  });
5
5
 
6
+ export const publicReleaseTags = Object.freeze(['stable', 'beta']);
7
+
6
8
  // A project's @tencent:registry setting takes precedence over npx --registry.
7
9
  export function internalRegistryArgs(packageName) {
8
10
  return packageName === distributionTargets.internal.package ? ['--@tencent:registry=' + distributionTargets.internal.registry] : [];
@@ -2,17 +2,45 @@ import path from 'node:path';
2
2
  import { lstat, readFile, mkdir, writeFile, rename, unlink } from 'node:fs/promises';
3
3
  import { randomUUID } from 'node:crypto';
4
4
 
5
+ // Compare the ordinary and extended spellings of drive and UNC paths.
6
+ // Verbatim-only names (e.g. a trailing dot) may denote different files.
7
+ export function resolveFilePath(file) {
8
+ if (process.platform === 'win32' && file.startsWith('\\\\?\\')) {
9
+ const body = file.slice(4);
10
+ const drive = /^[a-z]:\\/i.test(body);
11
+ const unc = /^UNC\\[^\\]+\\[^\\]+(?:\\|$)/i.test(body);
12
+ if (drive || unc) {
13
+ const parts = body.slice(drive ? 3 : 4).split('\\');
14
+ const verbatimOnly = parts.some(part => /[ .]$|[<>:"/|?*\x00-\x1f]|^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|$)/i.test(part));
15
+ if (!verbatimOnly) return path.resolve(drive ? body : '\\\\' + body.slice(4));
16
+ }
17
+ }
18
+ return path.resolve(file);
19
+ }
20
+
21
+ export function sameFilePath(a, b) {
22
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
23
+ const left = resolveFilePath(a), right = resolveFilePath(b);
24
+ return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
25
+ }
26
+
27
+ export function isPathInside(root, file) {
28
+ const relative = path.relative(resolveFilePath(root), resolveFilePath(file));
29
+ return relative !== '' && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
30
+ }
31
+
5
32
  export async function optionalFile(file) {
6
33
  try { return await readFile(file, 'utf8'); }
7
34
  catch (error) { if (error.code !== 'ENOENT') throw error; return null; }
8
35
  }
9
36
 
10
37
  export async function assertPlainPath(file) {
11
- let current = path.resolve(file);
38
+ const target = resolveFilePath(file);
39
+ let current = target;
12
40
  for (;;) {
13
41
  try {
14
42
  const info = await lstat(current);
15
- if (info.isSymbolicLink() || (current === path.resolve(file) ? !info.isFile() : !info.isDirectory())) throw new Error('Refusing linked or invalid install path: ' + current);
43
+ if (info.isSymbolicLink() || (current === target ? !info.isFile() : !info.isDirectory())) throw new Error('Refusing linked or invalid install path: ' + current);
16
44
  } catch (error) { if (error.code !== 'ENOENT') throw error; }
17
45
  const parent = path.dirname(current); if (parent === current) break; current = parent;
18
46
  }
@@ -1,7 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { readFile } from 'node:fs/promises';
3
3
  import { createHash } from 'node:crypto';
4
- import { optionalFile, assertPlainPath } from './files.mjs';
4
+ import { optionalFile, assertPlainPath, sameFilePath } from './files.mjs';
5
5
 
6
6
  export function launcherPath(installationFile) {
7
7
  return installationFile.replace(/\.json$/, '') + '.launcher.mjs';
@@ -11,7 +11,7 @@ export async function planLauncher(installationFile, previous, packageRoot) {
11
11
  const entry = launcherPath(installationFile);
12
12
  await assertPlainPath(entry);
13
13
  const before = await optionalFile(entry);
14
- if (before !== null && (!previous || previous.entry !== entry || createHash('sha256').update(before).digest('hex') !== previous.sha256)) {
14
+ if (before !== null && (!path.isAbsolute(previous?.entry ?? '') || !sameFilePath(previous.entry, entry) || createHash('sha256').update(before).digest('hex') !== previous.sha256)) {
15
15
  throw new Error('Craft launcher ownership or integrity mismatch; preserve the file and repair the installation');
16
16
  }
17
17
  const source = packageRoot ? path.join(packageRoot, 'dist-server/launcher.mjs') : new URL('../launcher.mjs', import.meta.url);
@@ -23,10 +23,10 @@ export async function verifyLauncher(state, installationFile, connection) {
23
23
  if (connection?.env && (connection.env.CRAFT_SERVER_ID ?? 'craft') !== state.server_id) throw new Error('Craft launcher instance differs from its registration');
24
24
  if (!state.launcher) return { mode: 'legacy_versioned_entry' };
25
25
  const expected = launcherPath(installationFile);
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');
26
+ if (state.launcher.schema !== 1 || !path.isAbsolute(state.launcher.entry ?? '') || !sameFilePath(state.launcher.entry, expected) || !/^[a-f0-9]{64}$/.test(state.launcher.sha256 ?? '')) throw new Error('Invalid Craft fixed launcher identity');
27
27
  if (state.launcher.kind !== undefined) throw new Error('Unsupported Craft launcher; run the standard installer and reconnect');
28
28
  await assertPlainPath(expected);
29
29
  if (createHash('sha256').update(await readFile(expected)).digest('hex') !== state.launcher.sha256) throw new Error('Craft fixed launcher integrity mismatch');
30
- if (connection && path.resolve(connection.args?.[0] ?? '') !== path.resolve(expected)) throw new Error('Craft host configuration does not use the installed fixed launcher');
30
+ if (connection && !sameFilePath(connection.args?.[0], expected)) throw new Error('Craft host configuration does not use the installed fixed launcher');
31
31
  return { mode: 'fixed_entry', entry: expected };
32
32
  }
@@ -6,7 +6,7 @@ import { defaultProfileDataDir, getAppDataRoot } from '../core/app-paths.mjs';
6
6
  import { hostPaths, hostCommandOptions, installTargets } from './hosts.mjs';
7
7
  import { craftConfig, craftRegistrations, mergeConfig, importZcodeFallback } from './config.mjs';
8
8
  import { assertDshSharedScope } from './dsh-config.mjs';
9
- import { optionalFile, assertPlainPath, commitFiles } from './files.mjs';
9
+ import { optionalFile, assertPlainPath, commitFiles, sameFilePath, resolveFilePath } from './files.mjs';
10
10
  import { stageRuntime, stageRegistryRuntime, probeRuntime, getRuntimeIdentity } from './runtime.mjs';
11
11
  import { installationPath, readInstallation, readInstallationSnapshot, registryOrigin, installedSkillEntries, skillRuntimeIdentity, sameRuntimeIdentity, activationMode } from './installation-state.mjs';
12
12
  import { queryRegistry } from './updates.mjs';
@@ -144,7 +144,7 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
144
144
  const statePath = installationPath(stateRoot, host, paths.config, instance);
145
145
  const previousSnapshot = old?.env?.CRAFT_INSTALLATION_FILE ? await readInstallationSnapshot(old.env.CRAFT_INSTALLATION_FILE) : null;
146
146
  const previousState = previousSnapshot?.state;
147
- if (repair && (previousState?.schema !== 2 || path.relative(runtimeRoot, previousState.runtime_root) !== '')) {
147
+ if (repair && (previousState?.schema !== 2 || !sameFilePath(runtimeRoot, previousState.runtime_root))) {
148
148
  throw new Error('Repair requires the selected managed Craft installation and its original runtime root.');
149
149
  }
150
150
  if (previousState) checkInstanceBinding(previousState, host, paths, instance, old.env.CRAFT_INSTALLATION_FILE);
@@ -219,7 +219,7 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
219
219
  if (registryOrigin(target.origin.registry) !== plan.source.registry || !target.origin.integrity) throw new Error('Recorded Craft repair source or integrity is inconsistent');
220
220
  remote = { package: target.package, version: target.version, integrity: target.origin.integrity };
221
221
  } else if (selector !== 'package' || pkg.version !== target.version) {
222
- remote = await lookup({ ...plan.source, channel: target.version });
222
+ remote = await lookup(plan.source, { version: target.version });
223
223
  if (remote.package !== target.package || remote.version !== target.version || !remote.integrity) {
224
224
  throw new Error('Could not resolve the exact Craft version for repair; use the original installation package.');
225
225
  }
@@ -301,13 +301,13 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
301
301
  });
302
302
  if (verifiedExisting) for (const [host, result] of verifiedExisting) verifiedByHost.set(host, result);
303
303
  }
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();
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(resolveFilePath))].sort();
305
305
  for (const file of lockPaths) {
306
306
  await assertPlainPath(file); await mkdir(path.dirname(file), { recursive: true });
307
307
  stateLocks.push(await lockfile.lock(file, { realpath: false, stale: 120000, retries: 0 }));
308
308
  }
309
309
  // Never hold installation-state locks while waiting on launcher or GC.
310
- release = await lockfile.lock(runtimeRoot, { stale: 120000, retries: 0 });
310
+ release = await lockfile.lock(resolveFilePath(runtimeRoot), { stale: 120000, retries: 0 });
311
311
  await verifyPlans(plans);
312
312
  const published = new Map(), changes = [], results = [];
313
313
  for (const plan of plans) {
@@ -1,17 +1,16 @@
1
1
  import path from 'node:path';
2
2
  import { createHash } from 'node:crypto';
3
- import { optionalFile } from './files.mjs';
3
+ import { optionalFile, sameFilePath } from './files.mjs';
4
4
  import { parseVersion, requireForwardVersion } from './version-policy.mjs';
5
5
  import { hosts } from './hosts.mjs';
6
6
  import { instanceSkillName } from './instance-skill.mjs';
7
7
 
8
- export const defaultRegistry = 'https://registry.npmjs.org/';
8
+ const defaultRegistry = 'https://registry.npmjs.org/';
9
9
  export const activationMode = 'next_mcp_start';
10
10
  export function sameRuntimeIdentity(left, right) {
11
- const samePath = (a, b) => typeof a === 'string' && typeof b === 'string' && (process.platform === 'win32' ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b));
12
- return Boolean(left && right && left.package === right.package && left.version === right.version && left.build_id === right.build_id && samePath(left.package_root, right.package_root) && samePath(left.entry, right.entry));
11
+ return Boolean(left && right && left.package === right.package && left.version === right.version && left.build_id === right.build_id && sameFilePath(left.package_root, right.package_root) && sameFilePath(left.entry, right.entry));
13
12
  }
14
- export const managedSkillMarkers = Object.freeze({ 'craft-create': '<!-- craft-mcp:bootstrap:v1 -->', 'craft-update': '<!-- craft-mcp:update:v1 -->' });
13
+ const managedSkillMarkers = Object.freeze({ 'craft-create': '<!-- craft-mcp:bootstrap:v1 -->', 'craft-update': '<!-- craft-mcp:update:v1 -->' });
15
14
  export function installedSkillEntries(state) {
16
15
  if (state.skills === undefined) return [];
17
16
  if (!state.skills || typeof state.skills !== 'object' || Array.isArray(state.skills) || !state.skills['craft-create']) throw new Error('Invalid installed Skill destinations');
@@ -44,11 +43,11 @@ export function installationPath(stateRoot, host, config, serverId = 'craft') {
44
43
  return { id, file: path.join(stateRoot, id + '.json') };
45
44
  }
46
45
 
47
- export function validateIdentity(identity) {
46
+ function validateIdentity(identity) {
48
47
  if (!identity || typeof identity !== 'object') throw new Error('Missing Craft runtime identity');
49
48
  parseVersion(identity.version);
50
49
  if (!identity.package || !/^[a-f0-9]{64}$/.test(identity.build_id ?? '') || !path.isAbsolute(identity.package_root ?? '') || !path.isAbsolute(identity.entry ?? '')) throw new Error('Invalid Craft runtime identity');
51
- if (path.resolve(identity.entry) !== path.join(path.resolve(identity.package_root), 'bin', 'craft-mcp.mjs')) throw new Error('Craft entry is outside its runtime package');
50
+ if (!sameFilePath(identity.entry, path.join(identity.package_root, 'bin', 'craft-mcp.mjs'))) throw new Error('Craft entry is outside its runtime package');
52
51
  return identity;
53
52
  }
54
53
 
@@ -8,11 +8,11 @@ import { randomUUID } from 'node:crypto';
8
8
  import lockfile from 'proper-lockfile';
9
9
  import { readInstallation, sameRuntimeIdentity } from './installation-state.mjs';
10
10
  import { readRunningIdentity } from './runtime-identity.mjs';
11
- import { assertPlainPath } from './files.mjs';
11
+ import { assertPlainPath, isPathInside, resolveFilePath, sameFilePath } from './files.mjs';
12
12
  import { verifyLauncher, launcherPath } from './fixed-launcher.mjs';
13
13
 
14
14
  async function start() {
15
- const entry = path.resolve(process.argv[1]);
15
+ const entry = resolveFilePath(process.argv[1]);
16
16
  const loginPage = process.argv.length === 3 && process.argv[2] === '--workbuddy-login-page';
17
17
  const preview = process.argv.length === 3 && process.argv[2] === '--workbuddy-preview';
18
18
  const installationFile = entry.replace(/\.launcher\.mjs$/, '.json');
@@ -20,23 +20,27 @@ async function start() {
20
20
  await assertPlainPath(installationFile);
21
21
  const initial = await readInstallation(installationFile);
22
22
  await assertPlainPath(path.join(initial.runtime_root, '.path-check'));
23
- const unlock = await lockfile.lock(initial.runtime_root, { stale: 120000, retries: { retries: 240, minTimeout: 250, maxTimeout: 500 } });
23
+ // proper-lockfile uses callback fs.realpath, which can fail on extended Windows paths.
24
+ const unlock = await lockfile.lock(resolveFilePath(initial.runtime_root), { stale: 120000, retries: { retries: 240, minTimeout: 250, maxTimeout: 500 } });
24
25
  let identity, state, lease;
25
26
  try {
26
27
  state = await readInstallation(installationFile);
27
28
  if ((loginPage || preview) && (process.platform !== 'win32' || state.host !== 'workbuddy')) throw new Error('The Windows background task requires a WorkBuddy installation');
28
- if (state.runtime_root !== initial.runtime_root || state.schema !== 2) throw new Error('Craft installation changed or needs migration');
29
+ if (!sameFilePath(state.runtime_root, initial.runtime_root) || state.schema !== 2) throw new Error('Craft installation changed or needs migration');
29
30
  await verifyLauncher(state, installationFile, { args: [entry] });
30
- if (process.env.CRAFT_INSTALLATION_FILE && path.resolve(process.env.CRAFT_INSTALLATION_FILE) !== installationFile) throw new Error('Craft launcher installation scope mismatch');
31
+ if (process.env.CRAFT_INSTALLATION_FILE && !sameFilePath(process.env.CRAFT_INSTALLATION_FILE, installationFile)) throw new Error('Craft launcher installation scope mismatch');
31
32
  if (state.host === 'workbuddy' && state.login_data_dir && process.env.CRAFT_STANDALONE_PROBE !== '1') {
32
33
  process.env.CLIENT_DATA_DIR ||= state.login_data_dir;
33
34
  }
34
35
  for (const [key, expected] of Object.entries({ CRAFT_CLIENT_IDE: state.host, CRAFT_SERVER_ID: state.server_id, CLIENT_WORKSPACE_ROOT: state.workspace, CRAFT_WEB_URL: state.platform })) {
35
- if (process.env[key] && process.env[key] !== expected) throw new Error('Craft launcher scope mismatch: ' + key);
36
+ const value = process.env[key];
37
+ if (value && value !== expected) {
38
+ const sameWorkspace = key === 'CLIENT_WORKSPACE_ROOT' && path.isAbsolute(value) && sameFilePath(value, expected);
39
+ if (!sameWorkspace) throw new Error('Craft launcher scope mismatch: ' + key);
40
+ }
36
41
  process.env[key] = expected;
37
42
  }
38
- const relative = path.relative(path.resolve(state.runtime_root), state.target.package_root);
39
- if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) throw new Error('Craft target is outside the managed runtime root');
43
+ if (!isPathInside(state.runtime_root, state.target.package_root)) throw new Error('Craft target is outside the managed runtime root');
40
44
  await assertPlainPath(state.target.entry);
41
45
  identity = await readRunningIdentity(state.target.package_root, { managed: true });
42
46
  if (!sameRuntimeIdentity(identity, state.target)) throw new Error('Craft target and installed runtime identity differ; run doctor for the selected instance');
@@ -16,7 +16,7 @@ export function readOpenCodeConfig(text) {
16
16
 
17
17
  // Installation state and probes use one internal stdio shape. Host files retain
18
18
  // their native command array and environment fields, including V1 compatibility.
19
- export function normalizeOpenCodeConnection(value) {
19
+ function normalizeOpenCodeConnection(value) {
20
20
  if (!object(value)) return value;
21
21
  const next = { ...value };
22
22
  if (Array.isArray(value.command)) { next.command = value.command[0]; next.args = value.command.slice(1); }