@craft_eco/craft-mcp 0.1.29 → 0.1.30
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.
- package/README.md +10 -55
- package/bin/craft-mcp.mjs +4 -1
- package/dist-server/game-workflow/check.mjs +3 -2
- package/dist-server/game-workflow/context-state.mjs +67 -67
- package/dist-server/game-workflow/draft-archive.mjs +147 -2
- package/dist-server/game-workflow/draft-upload-identity.mjs +11 -0
- package/dist-server/game-workflow/draft-uploads.mjs +105 -60
- package/dist-server/game-workflow/local-context.mjs +62 -62
- package/dist-server/game-workflow/native-context.mjs +289 -289
- package/dist-server/game-workflow/project-bundles.mjs +246 -246
- package/dist-server/game-workflow/project-context.mjs +8 -8
- package/dist-server/game-workflow/projects.mjs +6 -4
- package/dist-server/game-workflow/tasks.mjs +1 -1
- package/dist-server/game-workflow/work-scope.mjs +7 -7
- package/dist-server/integrations/config.mjs +145 -145
- package/dist-server/integrations/connect.mjs +36 -0
- package/dist-server/integrations/connection-handoff.mjs +36 -42
- package/dist-server/integrations/dsh-config.mjs +182 -182
- package/dist-server/integrations/files.mjs +54 -54
- package/dist-server/integrations/fixed-launcher.mjs +31 -0
- package/dist-server/integrations/host-reload.mjs +19 -0
- package/dist-server/integrations/hosts.mjs +55 -55
- package/dist-server/integrations/install.mjs +223 -205
- package/dist-server/integrations/installation-state.mjs +84 -84
- package/dist-server/integrations/launcher-start.mjs +52 -0
- package/dist-server/integrations/npm-diagnostics.mjs +32 -0
- package/dist-server/integrations/runtime-gc.mjs +191 -188
- package/dist-server/integrations/runtime-identity.mjs +22 -0
- package/dist-server/integrations/runtime.mjs +111 -126
- package/dist-server/integrations/updates.mjs +258 -225
- package/dist-server/integrations/version-policy.mjs +32 -32
- package/dist-server/launcher.mjs +1845 -0
- package/dist-server/mcp/control-panel.mjs +8 -23
- package/dist-server/mcp/server.mjs +31 -80
- package/dist-server/mcp/update-session.mjs +107 -92
- package/dist-server/upstream/craft-aigc.mjs +43 -16
- package/dist-server/upstream/draft-source.mjs +29 -0
- package/package.json +3 -2
- package/resources/context-filter-report.json +1 -1
- package/resources/craft-create/SKILL.md +19 -19
- package/resources/craft-update/SKILL.md +9 -11
- package/resources/targets/claude/js/bootstrap/SKILL.md +3 -1
- package/resources/targets/claude/js/context-filter-report.json +1 -1
- package/resources/targets/claude/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/claude/js/js/bundle.json +7 -7
- package/resources/targets/claude/js/recovery.md +5 -1
- package/resources/targets/claude/js/target.json +1 -1
- package/resources/targets/claude/js3d/bootstrap/SKILL.md +3 -1
- package/resources/targets/claude/js3d/context-filter-report.json +1 -1
- package/resources/targets/claude/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/claude/js3d/js3d/bundle.json +7 -7
- package/resources/targets/claude/js3d/recovery.md +5 -1
- package/resources/targets/claude/js3d/target.json +1 -1
- package/resources/targets/codebuddy/js/bootstrap/SKILL.md +3 -1
- package/resources/targets/codebuddy/js/context-filter-report.json +1 -1
- package/resources/targets/codebuddy/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/codebuddy/js/js/bundle.json +7 -7
- package/resources/targets/codebuddy/js/recovery.md +5 -1
- package/resources/targets/codebuddy/js/target.json +1 -1
- package/resources/targets/codebuddy/js3d/bootstrap/SKILL.md +3 -1
- package/resources/targets/codebuddy/js3d/context-filter-report.json +1 -1
- package/resources/targets/codebuddy/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/codebuddy/js3d/js3d/bundle.json +7 -7
- package/resources/targets/codebuddy/js3d/recovery.md +5 -1
- package/resources/targets/codebuddy/js3d/target.json +1 -1
- package/resources/targets/codex/js/bootstrap/SKILL.md +2 -4
- package/resources/targets/codex/js/context-filter-report.json +1 -1
- package/resources/targets/codex/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/codex/js/js/bundle.json +7 -7
- package/resources/targets/codex/js/recovery.md +3 -3
- package/resources/targets/codex/js/target.json +1 -1
- package/resources/targets/codex/js3d/bootstrap/SKILL.md +2 -4
- package/resources/targets/codex/js3d/context-filter-report.json +1 -1
- package/resources/targets/codex/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/codex/js3d/js3d/bundle.json +7 -7
- package/resources/targets/codex/js3d/recovery.md +3 -3
- package/resources/targets/codex/js3d/target.json +1 -1
- package/resources/targets/cursor/js/bootstrap/SKILL.md +3 -1
- package/resources/targets/cursor/js/context-filter-report.json +1 -1
- package/resources/targets/cursor/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/cursor/js/js/bundle.json +7 -7
- package/resources/targets/cursor/js/recovery.md +5 -1
- package/resources/targets/cursor/js/target.json +1 -1
- package/resources/targets/cursor/js3d/bootstrap/SKILL.md +3 -1
- package/resources/targets/cursor/js3d/context-filter-report.json +1 -1
- package/resources/targets/cursor/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/cursor/js3d/js3d/bundle.json +7 -7
- package/resources/targets/cursor/js3d/recovery.md +5 -1
- package/resources/targets/cursor/js3d/target.json +1 -1
- package/resources/targets/dsh/js/bootstrap/SKILL.md +3 -1
- package/resources/targets/dsh/js/context-filter-report.json +1 -1
- package/resources/targets/dsh/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/dsh/js/js/bundle.json +7 -7
- package/resources/targets/dsh/js/recovery.md +5 -1
- package/resources/targets/dsh/js/target.json +1 -1
- package/resources/targets/dsh/js3d/bootstrap/SKILL.md +3 -1
- package/resources/targets/dsh/js3d/context-filter-report.json +1 -1
- package/resources/targets/dsh/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/dsh/js3d/js3d/bundle.json +7 -7
- package/resources/targets/dsh/js3d/recovery.md +5 -1
- package/resources/targets/dsh/js3d/target.json +1 -1
- package/resources/targets/index.json +32 -32
- package/resources/targets/kimi/js/bootstrap/SKILL.md +3 -1
- package/resources/targets/kimi/js/context-filter-report.json +1 -1
- package/resources/targets/kimi/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/kimi/js/js/bundle.json +7 -7
- package/resources/targets/kimi/js/recovery.md +5 -1
- package/resources/targets/kimi/js/target.json +1 -1
- package/resources/targets/kimi/js3d/bootstrap/SKILL.md +3 -1
- package/resources/targets/kimi/js3d/context-filter-report.json +1 -1
- package/resources/targets/kimi/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/kimi/js3d/js3d/bundle.json +7 -7
- package/resources/targets/kimi/js3d/recovery.md +5 -1
- package/resources/targets/kimi/js3d/target.json +1 -1
- package/resources/targets/workbuddy/js/bootstrap/SKILL.md +22 -24
- package/resources/targets/workbuddy/js/context-filter-report.json +1 -1
- package/resources/targets/workbuddy/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/workbuddy/js/js/bundle.json +8 -8
- package/resources/targets/workbuddy/js/js/context/AGENTS.md +29 -29
- package/resources/targets/workbuddy/js/recovery.md +19 -19
- package/resources/targets/workbuddy/js/target.json +1 -1
- package/resources/targets/workbuddy/js3d/bootstrap/SKILL.md +22 -24
- package/resources/targets/workbuddy/js3d/context-filter-report.json +1 -1
- package/resources/targets/workbuddy/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/workbuddy/js3d/js3d/bundle.json +8 -8
- package/resources/targets/workbuddy/js3d/js3d/context/AGENTS.md +30 -30
- package/resources/targets/workbuddy/js3d/recovery.md +19 -19
- package/resources/targets/workbuddy/js3d/target.json +1 -1
- package/resources/targets/zcode/js/bootstrap/SKILL.md +3 -1
- package/resources/targets/zcode/js/context-filter-report.json +1 -1
- package/resources/targets/zcode/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/zcode/js/js/bundle.json +7 -7
- package/resources/targets/zcode/js/recovery.md +5 -1
- package/resources/targets/zcode/js/target.json +1 -1
- package/resources/targets/zcode/js3d/bootstrap/SKILL.md +3 -1
- package/resources/targets/zcode/js3d/context-filter-report.json +1 -1
- package/resources/targets/zcode/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/zcode/js3d/js3d/bundle.json +7 -7
- package/resources/targets/zcode/js3d/recovery.md +5 -1
- package/resources/targets/zcode/js3d/target.json +1 -1
- package/vendor/craft-runtime/SOURCE.json +4 -4
- package/vendor/craft-runtime/package.json +1 -1
- package/dist-server/game-workflow/publication-materials.mjs +0 -92
- package/dist-server/game-workflow/publications.mjs +0 -168
- package/dist-server/game-workflow/publish-capture-worker.mjs +0 -57
- package/dist-server/game-workflow/publish-capture.mjs +0 -75
- package/dist-server/mcp/publication-page.html +0 -86
- package/dist-server/mcp/publication-page.mjs +0 -375
- package/dist-server/mcp/publication-preview.mjs +0 -63
- package/dist-server/mcp/publication-tools.mjs +0 -22
- package/dist-server/mcp/publish-panel.mjs +0 -210
- package/dist-server/upstream/publication-transport.mjs +0 -101
|
@@ -1,246 +1,246 @@
|
|
|
1
|
-
import path from 'node:path';
|
|
2
|
-
import { cp, mkdir, mkdtemp, readFile, writeFile, lstat, rename, rm } from 'node:fs/promises';
|
|
3
|
-
import { safeProjectFile } from './asset-import.mjs';
|
|
4
|
-
import { loadEngineResource } from './engines.mjs';
|
|
5
|
-
import { verifyBundle } from './bundle-files.mjs';
|
|
6
|
-
import lockfile from 'proper-lockfile';
|
|
7
|
-
import { atomicJson } from './request-store.mjs';
|
|
8
|
-
import { hosts } from '../integrations/hosts.mjs';
|
|
9
|
-
import { isDeepStrictEqual } from 'node:util';
|
|
10
|
-
import { localContextPath } from './local-context.mjs';
|
|
11
|
-
import { contextLayoutSchema, schema4Hosts, nativeContextPath, inspectNativeContext, materializeNativeContext, preflightNativeContext, recoverNativeContext, recoverLegacyNativeContexts, retireLegacyContext, resolveNativeContext } from './native-context.mjs';
|
|
12
|
-
|
|
13
|
-
export const contextLock = '.craft/context-lock.json';
|
|
14
|
-
export async function readContextLock(project, engine) {
|
|
15
|
-
let lock;
|
|
16
|
-
try { lock = JSON.parse(await readFile(await safeProjectFile(project,contextLock),'utf8')); }
|
|
17
|
-
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
18
|
-
if(lock?.schema>contextLayoutSchema) throw new Error('Project context layout requires a newer Craft runtime; reconnect before preparing');
|
|
19
|
-
const validEntry = value => value && /^[a-f0-9]{64}$/.test(value.bundle_id) && typeof value.source_revision === 'string' && value.source_revision.length > 0;
|
|
20
|
-
if (!lock || lock.engine !== engine || (lock.schema === 1 ? !validEntry(lock) : ![2,3,4,contextLayoutSchema].includes(lock.schema) ||
|
|
21
|
-
!lock.compatibility || typeof lock.compatibility !== 'object' || Array.isArray(lock.compatibility) ||
|
|
22
|
-
!lock.contexts || typeof lock.contexts !== 'object' || Array.isArray(lock.contexts) || !Object.keys(lock.contexts).length ||
|
|
23
|
-
Object.entries(lock.contexts).some(([host,value])=>!Object.hasOwn(hosts,host) || (lock.schema===4 && !schema4Hosts.includes(host)) || !validEntry(value) ||
|
|
24
|
-
(value.path !== undefined && value.path !== (lock.schema >= 4 ? nativeContextPath(host,lock.schema) : localContextPath(host,engine,value.bundle_id)))) ||
|
|
25
|
-
(lock.schema >= 3 && lock.policy !== 'follow-installed') ||
|
|
26
|
-
(lock.schema >= 4 && (!lock.active_hosts || Array.isArray(lock.active_hosts) || Object.entries(lock.active_hosts).some(([directory,host])=>!Object.hasOwn(hosts,host) || nativeContextPath(host,lock.schema)!==directory || !lock.contexts[host]))))) throw new Error('Invalid project context lock or engine mismatch; restore the project lock from version control');
|
|
27
|
-
return lock;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export function contextBinding(lock, host, engine) {
|
|
31
|
-
if (!lock) return {status:'unbound',action:'Run craft_game_prepare to validate and bind this existing project; source files are preserved'};
|
|
32
|
-
if (lock.schema === 1) return {status:'bound',...lock,context_host:'legacy'};
|
|
33
|
-
const entry = lock.contexts[host];
|
|
34
|
-
return entry ? {status:'bound',schema:lock.schema,engine,context_host:host,...entry,contexts:lock.contexts,...(lock.policy ? {policy:lock.policy} : {})}
|
|
35
|
-
: {status:'host_unbound',schema:lock.schema,engine,context_host:host,contexts:lock.contexts,action:'Run craft_game_prepare to attach this host without changing existing host bindings'};
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export async function checkProjectCompatibility(project, bundle) {
|
|
39
|
-
const runtime = JSON.parse(await readFile(await safeProjectFile(project,'game-runtime.json'),'utf8'));
|
|
40
|
-
const pkg = JSON.parse(await readFile(await safeProjectFile(project,'package.json'),'utf8'));
|
|
41
|
-
const c = bundle.compatibility;
|
|
42
|
-
// Exact versions are the tested contract. Widen only with engine-specific validation.
|
|
43
|
-
if (runtime.version !== c.runtime_version || pkg.dependencies?.[c.dependency] !== c.dependency_version) {
|
|
44
|
-
throw new Error('Incompatible project runtime/dependency for '+bundle.engine+' context '+bundle.id+
|
|
45
|
-
'; expected runtime '+c.runtime_version+' and '+c.dependency+' '+c.dependency_version+'. Restore matching project versions or explicitly migrate and validate the engine bundle');
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
async function regularDirectory(directory) {
|
|
50
|
-
await mkdir(directory,{recursive:true});
|
|
51
|
-
const stat = await lstat(directory);
|
|
52
|
-
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Context cache must not contain directory links');
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export class ProjectBundles {
|
|
56
|
-
constructor(state, engines, host = 'generic') { this.cache = path.join(state,'context-bundles'); this.engines = engines; this.host = host; }
|
|
57
|
-
async retain(selected) {
|
|
58
|
-
await regularDirectory(this.cache);
|
|
59
|
-
const {engine,bundle,resources} = selected, target = path.join(this.cache,bundle.id);
|
|
60
|
-
try { await lstat(target); await verifyBundle(target,engine,bundle.id); return; }
|
|
61
|
-
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
62
|
-
const staging = await mkdtemp(path.join(this.cache,'.staging-'));
|
|
63
|
-
try {
|
|
64
|
-
for (const name of [...Object.keys(bundle.files),engine+'/bundle.json']) {
|
|
65
|
-
await mkdir(path.dirname(path.join(staging,name)),{recursive:true});
|
|
66
|
-
await cp(path.join(resources,name),path.join(staging,name),{dereference:false});
|
|
67
|
-
}
|
|
68
|
-
await verifyBundle(staging,engine,bundle.id);
|
|
69
|
-
try { await rename(staging,target); }
|
|
70
|
-
catch (error) {
|
|
71
|
-
if (!['EEXIST','ENOTEMPTY','EPERM'].includes(error.code)) throw error;
|
|
72
|
-
await verifyBundle(target,engine,bundle.id);
|
|
73
|
-
}
|
|
74
|
-
} finally { await rm(staging,{recursive:true,force:true}); }
|
|
75
|
-
}
|
|
76
|
-
async resolve(project, engine, lock) {
|
|
77
|
-
if (this.engines[engine].host) {
|
|
78
|
-
await checkProjectCompatibility(project,this.engines[engine].bundle);
|
|
79
|
-
return resolveNativeContext(project,this.engines[engine],lock);
|
|
80
|
-
}
|
|
81
|
-
if (lock?.schema >= 3) throw new Error('This project requires an explicit host and a Craft runtime supporting automatic context sync');
|
|
82
|
-
if (!lock) throw new Error('Project context is unbound; run craft_game_prepare to validate and bind the existing game without resetting its source');
|
|
83
|
-
const entry = lock.schema === 1 ? lock : lock.contexts[this.host];
|
|
84
|
-
if (!entry) throw new Error('Project context is unbound for host '+this.host+'; run craft_game_prepare to attach this host');
|
|
85
|
-
const current = this.engines[engine];
|
|
86
|
-
if (current.bundle.id !== entry.bundle_id && (await lstat(this.cache).catch(error=>{
|
|
87
|
-
if (error.code === 'ENOENT') return null;
|
|
88
|
-
throw error;
|
|
89
|
-
}))?.isSymbolicLink()) throw new Error('Context cache must not contain directory links');
|
|
90
|
-
let resources = current.bundle.id === entry.bundle_id ? current.resources : path.join(this.cache,entry.bundle_id);
|
|
91
|
-
if (lock.schema === 1 && current.legacyResources) {
|
|
92
|
-
const legacy = await verifyBundle(current.legacyResources,engine);
|
|
93
|
-
if (legacy.id === entry.bundle_id) resources = current.legacyResources;
|
|
94
|
-
}
|
|
95
|
-
let selected;
|
|
96
|
-
try { selected = await loadEngineResource(resources,engine,entry.bundle_id,lock.schema === 2 ? this.host : undefined); }
|
|
97
|
-
catch (error) {
|
|
98
|
-
if (error.code === 'ENOENT') throw new Error('Missing pinned context bundle '+entry.bundle_id+' ('+engine+', source '+entry.source_revision+'). Restore the matching Craft distribution or its context-bundles cache; the project has not been upgraded');
|
|
99
|
-
throw error;
|
|
100
|
-
}
|
|
101
|
-
if (selected.bundle.source_revision !== entry.source_revision) throw new Error('Project context source revision mismatch');
|
|
102
|
-
if (lock.schema === 1 && selected.bundle.schema !== 1) throw new Error('Legacy lock cannot select a host-specific context; restore the schema 2 binding');
|
|
103
|
-
if (lock.schema === 2 && (!isDeepStrictEqual(lock.compatibility,selected.bundle.compatibility) || entry.version !== selected.bundle.version)) throw new Error('Project context version or compatibility mismatch');
|
|
104
|
-
await checkProjectCompatibility(project,selected.bundle);
|
|
105
|
-
return selected;
|
|
106
|
-
}
|
|
107
|
-
async bind(project, engine, options = {}) {
|
|
108
|
-
if (this.engines[engine].host) return (await this.synchronize(project,engine,{...options,allowAttach:true})).lock;
|
|
109
|
-
const file = await safeProjectFile(project,contextLock,true);
|
|
110
|
-
const release = await lockfile.lock(file,{realpath:false,stale:30000,retries:{retries:10,minTimeout:50,maxTimeout:250}});
|
|
111
|
-
try { return await this.bindLocked(project,engine,options); }
|
|
112
|
-
finally { await release(); }
|
|
113
|
-
}
|
|
114
|
-
async synchronize(project, engine, {allowAttach = false, upgrade_context, context_bundle_id, finalize, guard=async()=>{}} = {}) {
|
|
115
|
-
const file = await safeProjectFile(project,contextLock,true);
|
|
116
|
-
const release = await lockfile.lock(file,{realpath:false,stale:30000,retries:{retries:20,minTimeout:30,maxTimeout:100}});
|
|
117
|
-
try {
|
|
118
|
-
const existing = await readContextLock(project,engine), source = this.engines[engine];
|
|
119
|
-
if (!source.host) throw new Error('Automatic context sync requires an explicit supported host');
|
|
120
|
-
if (upgrade_context !== undefined && typeof upgrade_context !== 'boolean') throw new Error('upgrade_context must be boolean');
|
|
121
|
-
if (context_bundle_id !== undefined && context_bundle_id !== source.bundle.id) throw new Error('Contexts follow the installed release; select the desired MCP release instead of pinning an older context');
|
|
122
|
-
const previous = existing?.schema === 1 ? undefined : existing?.contexts[this.host];
|
|
123
|
-
if (!allowAttach && !existing) throw new Error('Project context is unbound; run craft_game_prepare');
|
|
124
|
-
if (!allowAttach && existing?.schema !== 1 && !previous) throw new Error('Project context is unbound for host '+this.host+'; run craft_game_prepare');
|
|
125
|
-
// Recheck the installed source before writing any project files.
|
|
126
|
-
const current = await loadEngineResource(source.resources,engine,source.bundle.id,this.host);
|
|
127
|
-
await checkProjectCompatibility(project,current.bundle);
|
|
128
|
-
if (existing?.schema === 1) {
|
|
129
|
-
const legacy = await verifyBundle(source.legacyResources,engine,existing.bundle_id);
|
|
130
|
-
if (legacy.schema !== 1 || legacy.source_revision !== existing.source_revision) throw new Error('Legacy lock cannot select a host-specific context');
|
|
131
|
-
} else if (existing && !isDeepStrictEqual(existing.compatibility,current.bundle.compatibility)) throw new Error('New context is incompatible with the project; migrate and validate its engine runtime before syncing');
|
|
132
|
-
if (previous && previous.bundle_id !== current.bundle.id) {
|
|
133
|
-
if (!/^\d+\.\d+\.\d+$/.test(previous.version ?? '')) throw new Error('Invalid previous context version');
|
|
134
|
-
const difference = current.bundle.version.split('.').map((n,i)=>Number(n)-Number(previous.version.split('.')[i])).find(n=>n !== 0) ?? 0;
|
|
135
|
-
if (difference <= 0) throw new Error('Installed context is older or has a conflicting version; reconnect using the newer Craft runtime');
|
|
136
|
-
}
|
|
137
|
-
await guard();
|
|
138
|
-
await recoverLegacyNativeContexts(project,existing,guard);
|
|
139
|
-
const contexts = {}, candidates = new Map();
|
|
140
|
-
// Every host has its own directory. Layout migration may need to attach the
|
|
141
|
-
// two previously shared Buddy surfaces, but leaves other bound hosts at their
|
|
142
|
-
// existing versions. Normal schema-5 prepares update only the selected host.
|
|
143
|
-
for(const host of ['workbuddy',...Object.keys(hosts).filter(host=>host!=='workbuddy')]) {
|
|
144
|
-
const old=existing?.schema!==1 ? existing?.contexts?.[host] : undefined;
|
|
145
|
-
const oldPath=existing?.schema>=4 ? nativeContextPath(host,existing.schema) : null;
|
|
146
|
-
if(host!==this.host && old && oldPath===nativeContextPath(host) && existing.active_hosts?.[oldPath]===host) {
|
|
147
|
-
const actual=existing.schema===contextLayoutSchema ? null : await inspectNativeContext(project,host,engine,{schema:existing.schema});
|
|
148
|
-
if(!actual || (actual.manifest?.bundle_id===old.bundle_id && actual.manifest.source_revision===old.source_revision && actual.manifest.version===old.version)) {
|
|
149
|
-
contexts[host]={...old,path:oldPath};
|
|
150
|
-
continue;
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
const peer=host===this.host ? current : await loadEngineResource(path.join(source.legacyResources,'targets',host,engine),engine,undefined,host);
|
|
154
|
-
await checkProjectCompatibility(project,peer.bundle);
|
|
155
|
-
if(!isDeepStrictEqual(peer.bundle.compatibility,current.bundle.compatibility)) throw new Error('Installed host contexts have incompatible engine contracts');
|
|
156
|
-
if(old && old.bundle_id!==peer.bundle.id) {
|
|
157
|
-
const difference=peer.bundle.version.split('.').map((n,i)=>Number(n)-Number(old.version?.split('.')[i])).find(n=>n!==0)??0;
|
|
158
|
-
if(!Number.isFinite(difference)||difference<=0) throw new Error('Installed context is older or has a conflicting version for '+host);
|
|
159
|
-
}
|
|
160
|
-
candidates.set(host,peer);
|
|
161
|
-
}
|
|
162
|
-
await guard();
|
|
163
|
-
const legacyBuddy=existing && existing.schema<contextLayoutSchema
|
|
164
|
-
? await inspectNativeContext(project,'workbuddy',engine,{schema:4}) : null;
|
|
165
|
-
// A previous process may have committed the old physical directory before
|
|
166
|
-
// committing its lock. Protect that newer on-disk version during migration.
|
|
167
|
-
if(legacyBuddy?.manifest) {
|
|
168
|
-
const published=legacyBuddy.manifest, desired=candidates.get('workbuddy').bundle;
|
|
169
|
-
if(published.bundle_id!==desired.id) {
|
|
170
|
-
const difference=desired.version.split('.').map((n,i)=>Number(n)-Number(published.version.split('.')[i])).find(n=>n!==0)??0;
|
|
171
|
-
if(!Number.isFinite(difference)||difference<=0) throw new Error('Installed WorkBuddy context is older or has a conflicting version with the legacy published context');
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
const installed={};
|
|
175
|
-
const legacyBinding=legacyBuddy?.manifest;
|
|
176
|
-
for(const [host,peer] of candidates) {
|
|
177
|
-
await recoverNativeContext(project,host,guard);
|
|
178
|
-
await preflightNativeContext(project,peer,{legacyBinding:host==='codebuddy' ? legacyBinding : undefined});
|
|
179
|
-
}
|
|
180
|
-
// Publish WorkBuddy before repurposing an old WorkBuddy-owned .codebuddy.
|
|
181
|
-
// Each publication retains a durable backup and resumes after interruption.
|
|
182
|
-
for(const [host,peer] of candidates) {
|
|
183
|
-
const peerLocal=await materializeNativeContext(project,peer,guard,{legacyBinding:host==='codebuddy' ? legacyBinding : undefined});
|
|
184
|
-
contexts[host]={bundle_id:peer.bundle.id,source_revision:peer.bundle.source_revision,version:peer.bundle.version,path:peerLocal.relative};
|
|
185
|
-
installed[host]=peerLocal;
|
|
186
|
-
}
|
|
187
|
-
const local=installed[this.host];
|
|
188
|
-
const orderedContexts=Object.fromEntries(Object.entries(contexts).sort(([a],[b])=>a.localeCompare(b)));
|
|
189
|
-
const lock = {schema:contextLayoutSchema,policy:'follow-installed',engine,compatibility:current.bundle.compatibility,
|
|
190
|
-
contexts:orderedContexts,
|
|
191
|
-
active_hosts:Object.fromEntries(Object.entries(orderedContexts).map(([host,value])=>[value.path,host])),
|
|
192
|
-
...(existing?.schema === 1 ? {legacy_binding:existing} : existing?.legacy_binding ? {legacy_binding:existing.legacy_binding} : {})};
|
|
193
|
-
const verifyPublished=async()=>{
|
|
194
|
-
for(const peer of candidates.values()) await resolveNativeContext(project,peer,lock);
|
|
195
|
-
};
|
|
196
|
-
// The readiness receipt hashes serialized lock bytes. Persist an order-only
|
|
197
|
-
// normalization too, otherwise preparing a different host can sign a lock
|
|
198
|
-
// representation that was never written to disk.
|
|
199
|
-
const changed = JSON.stringify(existing)!==JSON.stringify(lock);
|
|
200
|
-
await guard();
|
|
201
|
-
await verifyPublished();
|
|
202
|
-
if (changed) await atomicJson(file,lock);
|
|
203
|
-
const migrated=[];
|
|
204
|
-
if(existing?.schema===3) for(const [host,value] of Object.entries(existing.contexts)) {
|
|
205
|
-
const backup=await retireLegacyContext(project,host,engine,value.bundle_id);
|
|
206
|
-
if(backup) migrated.push({host,backup});
|
|
207
|
-
}
|
|
208
|
-
const sync = {policy:'follow-installed',location:'project',status:changed || local.materialized ? 'updated' : 'current',
|
|
209
|
-
version:current.bundle.version,bundle_id:current.bundle.id,directory:local.selected.resources,
|
|
210
|
-
...(existing?.schema===4 ? {layout_migration:{from:4,to:contextLayoutSchema,previous_active_hosts:existing.active_hosts}} : {}),
|
|
211
|
-
...(previous && previous.bundle_id !== current.bundle.id ? {previous_bundle_id:previous.bundle_id} : {}),...(local.backup ? {backup:local.backup} : {}),...(migrated.length ? {migrated} : {})};
|
|
212
|
-
local.selected.context.sync = sync;
|
|
213
|
-
local.selected.context.hosts = Object.fromEntries(Object.entries(lock.active_hosts).map(([directory,host])=>[host,path.join(project,directory)]));
|
|
214
|
-
local.selected.context.user_rules = path.join(project,'.craft/user-rules.md');
|
|
215
|
-
const completed=await finalize?.(lock,verifyPublished);
|
|
216
|
-
return {lock,selected:local.selected,sync,...completed};
|
|
217
|
-
} finally {await release();}
|
|
218
|
-
}
|
|
219
|
-
async bindLocked(project, engine, {upgrade_context = false, context_bundle_id} = {}) {
|
|
220
|
-
const existing = await readContextLock(project,engine);
|
|
221
|
-
const current = this.engines[engine];
|
|
222
|
-
if (typeof upgrade_context !== 'boolean' || (context_bundle_id !== undefined && (typeof context_bundle_id !== 'string' || !/^[a-f0-9]{64}$/.test(context_bundle_id) || upgrade_context))) throw new Error('Use either boolean upgrade_context or a valid context_bundle_id');
|
|
223
|
-
const changing = upgrade_context || !!context_bundle_id;
|
|
224
|
-
if (changing && !current.host) throw new Error('Context switching requires an explicit supported host');
|
|
225
|
-
const hasBinding = existing && (existing.schema === 1 || existing.contexts[this.host]);
|
|
226
|
-
// Verify the old binding before an explicit switch; never use an update to hide corruption.
|
|
227
|
-
if (hasBinding && changing) await this.resolve(project,engine,existing);
|
|
228
|
-
let selected;
|
|
229
|
-
if (hasBinding && !changing) selected = await this.resolve(project,engine,existing);
|
|
230
|
-
else if (context_bundle_id && current.bundle.id !== context_bundle_id) selected = await loadEngineResource(path.join(this.cache,context_bundle_id),engine,context_bundle_id,this.host);
|
|
231
|
-
else selected = await loadEngineResource(current.resources,engine,current.bundle.id,current.host);
|
|
232
|
-
await checkProjectCompatibility(project,selected.bundle);
|
|
233
|
-
if (existing?.schema === 2 && !isDeepStrictEqual(existing.compatibility,selected.bundle.compatibility)) throw new Error('Context is incompatible with the existing engine binding');
|
|
234
|
-
await this.retain(selected);
|
|
235
|
-
if (hasBinding && !changing) return existing;
|
|
236
|
-
const entry = {bundle_id:selected.bundle.id,source_revision:selected.bundle.source_revision,...(selected.bundle.version ? {version:selected.bundle.version} : {})};
|
|
237
|
-
const lock = selected.bundle.schema === 1 ? {schema:1,engine,...entry} : {
|
|
238
|
-
schema:2,engine,compatibility:selected.bundle.compatibility,
|
|
239
|
-
contexts:{...(existing?.schema === 2 ? existing.contexts : {}),[this.host]:entry},
|
|
240
|
-
...(existing?.schema === 1 ? {legacy_binding:existing} : existing?.legacy_binding ? {legacy_binding:existing.legacy_binding} : {})
|
|
241
|
-
};
|
|
242
|
-
const file = await safeProjectFile(project,contextLock,true);
|
|
243
|
-
await atomicJson(file,lock);
|
|
244
|
-
return lock;
|
|
245
|
-
}
|
|
246
|
-
}
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { cp, mkdir, mkdtemp, readFile, writeFile, lstat, rename, rm } from 'node:fs/promises';
|
|
3
|
+
import { safeProjectFile } from './asset-import.mjs';
|
|
4
|
+
import { loadEngineResource } from './engines.mjs';
|
|
5
|
+
import { verifyBundle } from './bundle-files.mjs';
|
|
6
|
+
import lockfile from 'proper-lockfile';
|
|
7
|
+
import { atomicJson } from './request-store.mjs';
|
|
8
|
+
import { hosts } from '../integrations/hosts.mjs';
|
|
9
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
10
|
+
import { localContextPath } from './local-context.mjs';
|
|
11
|
+
import { contextLayoutSchema, schema4Hosts, nativeContextPath, inspectNativeContext, materializeNativeContext, preflightNativeContext, recoverNativeContext, recoverLegacyNativeContexts, retireLegacyContext, resolveNativeContext } from './native-context.mjs';
|
|
12
|
+
|
|
13
|
+
export const contextLock = '.craft/context-lock.json';
|
|
14
|
+
export async function readContextLock(project, engine) {
|
|
15
|
+
let lock;
|
|
16
|
+
try { lock = JSON.parse(await readFile(await safeProjectFile(project,contextLock),'utf8')); }
|
|
17
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
18
|
+
if(lock?.schema>contextLayoutSchema) throw new Error('Project context layout requires a newer Craft runtime; reconnect before preparing');
|
|
19
|
+
const validEntry = value => value && /^[a-f0-9]{64}$/.test(value.bundle_id) && typeof value.source_revision === 'string' && value.source_revision.length > 0;
|
|
20
|
+
if (!lock || lock.engine !== engine || (lock.schema === 1 ? !validEntry(lock) : ![2,3,4,contextLayoutSchema].includes(lock.schema) ||
|
|
21
|
+
!lock.compatibility || typeof lock.compatibility !== 'object' || Array.isArray(lock.compatibility) ||
|
|
22
|
+
!lock.contexts || typeof lock.contexts !== 'object' || Array.isArray(lock.contexts) || !Object.keys(lock.contexts).length ||
|
|
23
|
+
Object.entries(lock.contexts).some(([host,value])=>!Object.hasOwn(hosts,host) || (lock.schema===4 && !schema4Hosts.includes(host)) || !validEntry(value) ||
|
|
24
|
+
(value.path !== undefined && value.path !== (lock.schema >= 4 ? nativeContextPath(host,lock.schema) : localContextPath(host,engine,value.bundle_id)))) ||
|
|
25
|
+
(lock.schema >= 3 && lock.policy !== 'follow-installed') ||
|
|
26
|
+
(lock.schema >= 4 && (!lock.active_hosts || Array.isArray(lock.active_hosts) || Object.entries(lock.active_hosts).some(([directory,host])=>!Object.hasOwn(hosts,host) || nativeContextPath(host,lock.schema)!==directory || !lock.contexts[host]))))) throw new Error('Invalid project context lock or engine mismatch; restore the project lock from version control');
|
|
27
|
+
return lock;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function contextBinding(lock, host, engine) {
|
|
31
|
+
if (!lock) return {status:'unbound',action:'Run craft_game_prepare to validate and bind this existing project; source files are preserved'};
|
|
32
|
+
if (lock.schema === 1) return {status:'bound',...lock,context_host:'legacy'};
|
|
33
|
+
const entry = lock.contexts[host];
|
|
34
|
+
return entry ? {status:'bound',schema:lock.schema,engine,context_host:host,...entry,contexts:lock.contexts,...(lock.policy ? {policy:lock.policy} : {})}
|
|
35
|
+
: {status:'host_unbound',schema:lock.schema,engine,context_host:host,contexts:lock.contexts,action:'Run craft_game_prepare to attach this host without changing existing host bindings'};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function checkProjectCompatibility(project, bundle) {
|
|
39
|
+
const runtime = JSON.parse(await readFile(await safeProjectFile(project,'game-runtime.json'),'utf8'));
|
|
40
|
+
const pkg = JSON.parse(await readFile(await safeProjectFile(project,'package.json'),'utf8'));
|
|
41
|
+
const c = bundle.compatibility;
|
|
42
|
+
// Exact versions are the tested contract. Widen only with engine-specific validation.
|
|
43
|
+
if (runtime.version !== c.runtime_version || pkg.dependencies?.[c.dependency] !== c.dependency_version) {
|
|
44
|
+
throw new Error('Incompatible project runtime/dependency for '+bundle.engine+' context '+bundle.id+
|
|
45
|
+
'; expected runtime '+c.runtime_version+' and '+c.dependency+' '+c.dependency_version+'. Restore matching project versions or explicitly migrate and validate the engine bundle');
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function regularDirectory(directory) {
|
|
50
|
+
await mkdir(directory,{recursive:true});
|
|
51
|
+
const stat = await lstat(directory);
|
|
52
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Context cache must not contain directory links');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export class ProjectBundles {
|
|
56
|
+
constructor(state, engines, host = 'generic') { this.cache = path.join(state,'context-bundles'); this.engines = engines; this.host = host; }
|
|
57
|
+
async retain(selected) {
|
|
58
|
+
await regularDirectory(this.cache);
|
|
59
|
+
const {engine,bundle,resources} = selected, target = path.join(this.cache,bundle.id);
|
|
60
|
+
try { await lstat(target); await verifyBundle(target,engine,bundle.id); return; }
|
|
61
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
62
|
+
const staging = await mkdtemp(path.join(this.cache,'.staging-'));
|
|
63
|
+
try {
|
|
64
|
+
for (const name of [...Object.keys(bundle.files),engine+'/bundle.json']) {
|
|
65
|
+
await mkdir(path.dirname(path.join(staging,name)),{recursive:true});
|
|
66
|
+
await cp(path.join(resources,name),path.join(staging,name),{dereference:false});
|
|
67
|
+
}
|
|
68
|
+
await verifyBundle(staging,engine,bundle.id);
|
|
69
|
+
try { await rename(staging,target); }
|
|
70
|
+
catch (error) {
|
|
71
|
+
if (!['EEXIST','ENOTEMPTY','EPERM'].includes(error.code)) throw error;
|
|
72
|
+
await verifyBundle(target,engine,bundle.id);
|
|
73
|
+
}
|
|
74
|
+
} finally { await rm(staging,{recursive:true,force:true}); }
|
|
75
|
+
}
|
|
76
|
+
async resolve(project, engine, lock) {
|
|
77
|
+
if (this.engines[engine].host) {
|
|
78
|
+
await checkProjectCompatibility(project,this.engines[engine].bundle);
|
|
79
|
+
return resolveNativeContext(project,this.engines[engine],lock);
|
|
80
|
+
}
|
|
81
|
+
if (lock?.schema >= 3) throw new Error('This project requires an explicit host and a Craft runtime supporting automatic context sync');
|
|
82
|
+
if (!lock) throw new Error('Project context is unbound; run craft_game_prepare to validate and bind the existing game without resetting its source');
|
|
83
|
+
const entry = lock.schema === 1 ? lock : lock.contexts[this.host];
|
|
84
|
+
if (!entry) throw new Error('Project context is unbound for host '+this.host+'; run craft_game_prepare to attach this host');
|
|
85
|
+
const current = this.engines[engine];
|
|
86
|
+
if (current.bundle.id !== entry.bundle_id && (await lstat(this.cache).catch(error=>{
|
|
87
|
+
if (error.code === 'ENOENT') return null;
|
|
88
|
+
throw error;
|
|
89
|
+
}))?.isSymbolicLink()) throw new Error('Context cache must not contain directory links');
|
|
90
|
+
let resources = current.bundle.id === entry.bundle_id ? current.resources : path.join(this.cache,entry.bundle_id);
|
|
91
|
+
if (lock.schema === 1 && current.legacyResources) {
|
|
92
|
+
const legacy = await verifyBundle(current.legacyResources,engine);
|
|
93
|
+
if (legacy.id === entry.bundle_id) resources = current.legacyResources;
|
|
94
|
+
}
|
|
95
|
+
let selected;
|
|
96
|
+
try { selected = await loadEngineResource(resources,engine,entry.bundle_id,lock.schema === 2 ? this.host : undefined); }
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (error.code === 'ENOENT') throw new Error('Missing pinned context bundle '+entry.bundle_id+' ('+engine+', source '+entry.source_revision+'). Restore the matching Craft distribution or its context-bundles cache; the project has not been upgraded');
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
if (selected.bundle.source_revision !== entry.source_revision) throw new Error('Project context source revision mismatch');
|
|
102
|
+
if (lock.schema === 1 && selected.bundle.schema !== 1) throw new Error('Legacy lock cannot select a host-specific context; restore the schema 2 binding');
|
|
103
|
+
if (lock.schema === 2 && (!isDeepStrictEqual(lock.compatibility,selected.bundle.compatibility) || entry.version !== selected.bundle.version)) throw new Error('Project context version or compatibility mismatch');
|
|
104
|
+
await checkProjectCompatibility(project,selected.bundle);
|
|
105
|
+
return selected;
|
|
106
|
+
}
|
|
107
|
+
async bind(project, engine, options = {}) {
|
|
108
|
+
if (this.engines[engine].host) return (await this.synchronize(project,engine,{...options,allowAttach:true})).lock;
|
|
109
|
+
const file = await safeProjectFile(project,contextLock,true);
|
|
110
|
+
const release = await lockfile.lock(file,{realpath:false,stale:30000,retries:{retries:10,minTimeout:50,maxTimeout:250}});
|
|
111
|
+
try { return await this.bindLocked(project,engine,options); }
|
|
112
|
+
finally { await release(); }
|
|
113
|
+
}
|
|
114
|
+
async synchronize(project, engine, {allowAttach = false, upgrade_context, context_bundle_id, finalize, guard=async()=>{}} = {}) {
|
|
115
|
+
const file = await safeProjectFile(project,contextLock,true);
|
|
116
|
+
const release = await lockfile.lock(file,{realpath:false,stale:30000,retries:{retries:20,minTimeout:30,maxTimeout:100}});
|
|
117
|
+
try {
|
|
118
|
+
const existing = await readContextLock(project,engine), source = this.engines[engine];
|
|
119
|
+
if (!source.host) throw new Error('Automatic context sync requires an explicit supported host');
|
|
120
|
+
if (upgrade_context !== undefined && typeof upgrade_context !== 'boolean') throw new Error('upgrade_context must be boolean');
|
|
121
|
+
if (context_bundle_id !== undefined && context_bundle_id !== source.bundle.id) throw new Error('Contexts follow the installed release; select the desired MCP release instead of pinning an older context');
|
|
122
|
+
const previous = existing?.schema === 1 ? undefined : existing?.contexts[this.host];
|
|
123
|
+
if (!allowAttach && !existing) throw new Error('Project context is unbound; run craft_game_prepare');
|
|
124
|
+
if (!allowAttach && existing?.schema !== 1 && !previous) throw new Error('Project context is unbound for host '+this.host+'; run craft_game_prepare');
|
|
125
|
+
// Recheck the installed source before writing any project files.
|
|
126
|
+
const current = await loadEngineResource(source.resources,engine,source.bundle.id,this.host);
|
|
127
|
+
await checkProjectCompatibility(project,current.bundle);
|
|
128
|
+
if (existing?.schema === 1) {
|
|
129
|
+
const legacy = await verifyBundle(source.legacyResources,engine,existing.bundle_id);
|
|
130
|
+
if (legacy.schema !== 1 || legacy.source_revision !== existing.source_revision) throw new Error('Legacy lock cannot select a host-specific context');
|
|
131
|
+
} else if (existing && !isDeepStrictEqual(existing.compatibility,current.bundle.compatibility)) throw new Error('New context is incompatible with the project; migrate and validate its engine runtime before syncing');
|
|
132
|
+
if (previous && previous.bundle_id !== current.bundle.id) {
|
|
133
|
+
if (!/^\d+\.\d+\.\d+$/.test(previous.version ?? '')) throw new Error('Invalid previous context version');
|
|
134
|
+
const difference = current.bundle.version.split('.').map((n,i)=>Number(n)-Number(previous.version.split('.')[i])).find(n=>n !== 0) ?? 0;
|
|
135
|
+
if (difference <= 0) throw new Error('Installed context is older or has a conflicting version; reconnect using the newer Craft runtime');
|
|
136
|
+
}
|
|
137
|
+
await guard();
|
|
138
|
+
await recoverLegacyNativeContexts(project,existing,guard);
|
|
139
|
+
const contexts = {}, candidates = new Map();
|
|
140
|
+
// Every host has its own directory. Layout migration may need to attach the
|
|
141
|
+
// two previously shared Buddy surfaces, but leaves other bound hosts at their
|
|
142
|
+
// existing versions. Normal schema-5 prepares update only the selected host.
|
|
143
|
+
for(const host of ['workbuddy',...Object.keys(hosts).filter(host=>host!=='workbuddy')]) {
|
|
144
|
+
const old=existing?.schema!==1 ? existing?.contexts?.[host] : undefined;
|
|
145
|
+
const oldPath=existing?.schema>=4 ? nativeContextPath(host,existing.schema) : null;
|
|
146
|
+
if(host!==this.host && old && oldPath===nativeContextPath(host) && existing.active_hosts?.[oldPath]===host) {
|
|
147
|
+
const actual=existing.schema===contextLayoutSchema ? null : await inspectNativeContext(project,host,engine,{schema:existing.schema});
|
|
148
|
+
if(!actual || (actual.manifest?.bundle_id===old.bundle_id && actual.manifest.source_revision===old.source_revision && actual.manifest.version===old.version)) {
|
|
149
|
+
contexts[host]={...old,path:oldPath};
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const peer=host===this.host ? current : await loadEngineResource(path.join(source.legacyResources,'targets',host,engine),engine,undefined,host);
|
|
154
|
+
await checkProjectCompatibility(project,peer.bundle);
|
|
155
|
+
if(!isDeepStrictEqual(peer.bundle.compatibility,current.bundle.compatibility)) throw new Error('Installed host contexts have incompatible engine contracts');
|
|
156
|
+
if(old && old.bundle_id!==peer.bundle.id) {
|
|
157
|
+
const difference=peer.bundle.version.split('.').map((n,i)=>Number(n)-Number(old.version?.split('.')[i])).find(n=>n!==0)??0;
|
|
158
|
+
if(!Number.isFinite(difference)||difference<=0) throw new Error('Installed context is older or has a conflicting version for '+host);
|
|
159
|
+
}
|
|
160
|
+
candidates.set(host,peer);
|
|
161
|
+
}
|
|
162
|
+
await guard();
|
|
163
|
+
const legacyBuddy=existing && existing.schema<contextLayoutSchema
|
|
164
|
+
? await inspectNativeContext(project,'workbuddy',engine,{schema:4}) : null;
|
|
165
|
+
// A previous process may have committed the old physical directory before
|
|
166
|
+
// committing its lock. Protect that newer on-disk version during migration.
|
|
167
|
+
if(legacyBuddy?.manifest) {
|
|
168
|
+
const published=legacyBuddy.manifest, desired=candidates.get('workbuddy').bundle;
|
|
169
|
+
if(published.bundle_id!==desired.id) {
|
|
170
|
+
const difference=desired.version.split('.').map((n,i)=>Number(n)-Number(published.version.split('.')[i])).find(n=>n!==0)??0;
|
|
171
|
+
if(!Number.isFinite(difference)||difference<=0) throw new Error('Installed WorkBuddy context is older or has a conflicting version with the legacy published context');
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const installed={};
|
|
175
|
+
const legacyBinding=legacyBuddy?.manifest;
|
|
176
|
+
for(const [host,peer] of candidates) {
|
|
177
|
+
await recoverNativeContext(project,host,guard);
|
|
178
|
+
await preflightNativeContext(project,peer,{legacyBinding:host==='codebuddy' ? legacyBinding : undefined});
|
|
179
|
+
}
|
|
180
|
+
// Publish WorkBuddy before repurposing an old WorkBuddy-owned .codebuddy.
|
|
181
|
+
// Each publication retains a durable backup and resumes after interruption.
|
|
182
|
+
for(const [host,peer] of candidates) {
|
|
183
|
+
const peerLocal=await materializeNativeContext(project,peer,guard,{legacyBinding:host==='codebuddy' ? legacyBinding : undefined});
|
|
184
|
+
contexts[host]={bundle_id:peer.bundle.id,source_revision:peer.bundle.source_revision,version:peer.bundle.version,path:peerLocal.relative};
|
|
185
|
+
installed[host]=peerLocal;
|
|
186
|
+
}
|
|
187
|
+
const local=installed[this.host];
|
|
188
|
+
const orderedContexts=Object.fromEntries(Object.entries(contexts).sort(([a],[b])=>a.localeCompare(b)));
|
|
189
|
+
const lock = {schema:contextLayoutSchema,policy:'follow-installed',engine,compatibility:current.bundle.compatibility,
|
|
190
|
+
contexts:orderedContexts,
|
|
191
|
+
active_hosts:Object.fromEntries(Object.entries(orderedContexts).map(([host,value])=>[value.path,host])),
|
|
192
|
+
...(existing?.schema === 1 ? {legacy_binding:existing} : existing?.legacy_binding ? {legacy_binding:existing.legacy_binding} : {})};
|
|
193
|
+
const verifyPublished=async()=>{
|
|
194
|
+
for(const peer of candidates.values()) await resolveNativeContext(project,peer,lock);
|
|
195
|
+
};
|
|
196
|
+
// The readiness receipt hashes serialized lock bytes. Persist an order-only
|
|
197
|
+
// normalization too, otherwise preparing a different host can sign a lock
|
|
198
|
+
// representation that was never written to disk.
|
|
199
|
+
const changed = JSON.stringify(existing)!==JSON.stringify(lock);
|
|
200
|
+
await guard();
|
|
201
|
+
await verifyPublished();
|
|
202
|
+
if (changed) await atomicJson(file,lock);
|
|
203
|
+
const migrated=[];
|
|
204
|
+
if(existing?.schema===3) for(const [host,value] of Object.entries(existing.contexts)) {
|
|
205
|
+
const backup=await retireLegacyContext(project,host,engine,value.bundle_id);
|
|
206
|
+
if(backup) migrated.push({host,backup});
|
|
207
|
+
}
|
|
208
|
+
const sync = {policy:'follow-installed',location:'project',status:changed || local.materialized ? 'updated' : 'current',
|
|
209
|
+
version:current.bundle.version,bundle_id:current.bundle.id,directory:local.selected.resources,
|
|
210
|
+
...(existing?.schema===4 ? {layout_migration:{from:4,to:contextLayoutSchema,previous_active_hosts:existing.active_hosts}} : {}),
|
|
211
|
+
...(previous && previous.bundle_id !== current.bundle.id ? {previous_bundle_id:previous.bundle_id} : {}),...(local.backup ? {backup:local.backup} : {}),...(migrated.length ? {migrated} : {})};
|
|
212
|
+
local.selected.context.sync = sync;
|
|
213
|
+
local.selected.context.hosts = Object.fromEntries(Object.entries(lock.active_hosts).map(([directory,host])=>[host,path.join(project,directory)]));
|
|
214
|
+
local.selected.context.user_rules = path.join(project,'.craft/user-rules.md');
|
|
215
|
+
const completed=await finalize?.(lock,verifyPublished);
|
|
216
|
+
return {lock,selected:local.selected,sync,...completed};
|
|
217
|
+
} finally {await release();}
|
|
218
|
+
}
|
|
219
|
+
async bindLocked(project, engine, {upgrade_context = false, context_bundle_id} = {}) {
|
|
220
|
+
const existing = await readContextLock(project,engine);
|
|
221
|
+
const current = this.engines[engine];
|
|
222
|
+
if (typeof upgrade_context !== 'boolean' || (context_bundle_id !== undefined && (typeof context_bundle_id !== 'string' || !/^[a-f0-9]{64}$/.test(context_bundle_id) || upgrade_context))) throw new Error('Use either boolean upgrade_context or a valid context_bundle_id');
|
|
223
|
+
const changing = upgrade_context || !!context_bundle_id;
|
|
224
|
+
if (changing && !current.host) throw new Error('Context switching requires an explicit supported host');
|
|
225
|
+
const hasBinding = existing && (existing.schema === 1 || existing.contexts[this.host]);
|
|
226
|
+
// Verify the old binding before an explicit switch; never use an update to hide corruption.
|
|
227
|
+
if (hasBinding && changing) await this.resolve(project,engine,existing);
|
|
228
|
+
let selected;
|
|
229
|
+
if (hasBinding && !changing) selected = await this.resolve(project,engine,existing);
|
|
230
|
+
else if (context_bundle_id && current.bundle.id !== context_bundle_id) selected = await loadEngineResource(path.join(this.cache,context_bundle_id),engine,context_bundle_id,this.host);
|
|
231
|
+
else selected = await loadEngineResource(current.resources,engine,current.bundle.id,current.host);
|
|
232
|
+
await checkProjectCompatibility(project,selected.bundle);
|
|
233
|
+
if (existing?.schema === 2 && !isDeepStrictEqual(existing.compatibility,selected.bundle.compatibility)) throw new Error('Context is incompatible with the existing engine binding');
|
|
234
|
+
await this.retain(selected);
|
|
235
|
+
if (hasBinding && !changing) return existing;
|
|
236
|
+
const entry = {bundle_id:selected.bundle.id,source_revision:selected.bundle.source_revision,...(selected.bundle.version ? {version:selected.bundle.version} : {})};
|
|
237
|
+
const lock = selected.bundle.schema === 1 ? {schema:1,engine,...entry} : {
|
|
238
|
+
schema:2,engine,compatibility:selected.bundle.compatibility,
|
|
239
|
+
contexts:{...(existing?.schema === 2 ? existing.contexts : {}),[this.host]:entry},
|
|
240
|
+
...(existing?.schema === 1 ? {legacy_binding:existing} : existing?.legacy_binding ? {legacy_binding:existing.legacy_binding} : {})
|
|
241
|
+
};
|
|
242
|
+
const file = await safeProjectFile(project,contextLock,true);
|
|
243
|
+
await atomicJson(file,lock);
|
|
244
|
+
return lock;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
@@ -9,7 +9,7 @@ import { hosts, clientIde, projectSkillPath } from '../integrations/hosts.mjs';
|
|
|
9
9
|
const start = '<!-- craft-mcp:project:start -->';
|
|
10
10
|
const end = '<!-- craft-mcp:project:end -->';
|
|
11
11
|
// Independent of engine bundle versions: generated recovery instructions evolve too.
|
|
12
|
-
export const entryPolicyVersion =
|
|
12
|
+
export const entryPolicyVersion = 9;
|
|
13
13
|
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
14
14
|
const normalizeLines = value => value.replace(/\r\n/g,'\n');
|
|
15
15
|
|
|
@@ -90,9 +90,10 @@ function recoveryEntries(name, engine, ide = 'generic', isolated = false) {
|
|
|
90
90
|
const body = isolated ? `Craft 工程名:\`${name}\`;引擎:\`${engine}\`。\n\n`
|
|
91
91
|
+ '本项目为各宿主分别维护上下文。' + Object.entries(hosts).map(([id,definition])=>`${definition.label ?? id} 读取 \`${nativeContextPath(id)}/AGENTS.md\``).join(',') + ';按所用宿主显式读取对应目录的 `workflow.md`、`recovery.md`、`knowledge/` 和 `skills/`。若当前宿主目录尚未提供,先完成下述 prepare 流程,不借用其他宿主的调优正文。\n\n'
|
|
92
92
|
+ '宿主可能兼容扫描其他目录;执行任务使用自身目录中的 Skill 正文,避免同名技能取到另一宿主的调优版本。\n\n'
|
|
93
|
-
+ `新会话首次处理本工程时调用 \`craft_game_info({"name":"${name}"})\`,核对 project 和 workspace,再调用 \`craft_update_check({"name":"${name}","
|
|
94
|
-
+ '
|
|
95
|
-
+ '
|
|
93
|
+
+ `新会话首次处理本工程时调用 \`craft_game_info({"name":"${name}"})\`,核对 project 和 workspace,再调用 \`craft_update_check({"name":"${name}","request_key":"resume-unique-key"})\` 检查 npm 与当前连接版本。MCP 的 workspace 必须是当前游戏父目录。\n\n`
|
|
94
|
+
+ '继续制作时,若检查返回 update_available=true 且 automatic_update_enabled=true,自动调用 `craft_update`(name、mode=auto、同一 request_key)安装兼容新版;尚待重连或不兼容时先处理该状态。确认可继续后调用 craft_game_prepare,传 mode=resume、name 和同一 request_key,轮询成功后保存 work_id/context_revision,重新读取本地入口和技能索引。prepare 也会执行更新检查;重试复用 request_key,当前 work 内保持原版本。\n\n'
|
|
95
|
+
+ '新版安装后在下次 MCP 启动或用户重连时加载,当前进程继续原版;不主动重载或结束已有工作。重连后核对实际版本、build_id、active_verified 与宿主范围,再恢复当前项目。\n\n'
|
|
96
|
+
+ '待重连时按 connection_handoff 提示用户;先完成后台任务、保存进度并 release,再重连 Craft。只有宿主实际提示信任时才由用户确认。只重试明确未开始的 prepare,不重放结果不明的操作。\n\n'
|
|
96
97
|
+ '读取 `SPEC/PROGRESS.md`、相关设计和源码;存在 `.craft/user-rules.md` 时一并读取。用户规则放在该文件或本文件管理段之外。官方正文由清单管理,更新前保留修改备份;游戏代码和用户进度保留。\n\n'
|
|
97
98
|
+ '纯查看无需 prepare,查询不改任何项目文件。制作期间沿用 work_id;结束或暂停后等待后台任务结束、记录进度并 craft_game_release。`.craft/context-lock.json` 只记录各宿主版本与校验状态,不作为正文目录。\n'
|
|
98
99
|
: recovery(name, engine);
|
|
@@ -101,10 +102,9 @@ function recoveryEntries(name, engine, ide = 'generic', isolated = false) {
|
|
|
101
102
|
const desiredSkill = `---\nname: craft-project\ndescription: 继续、修改、调试、验收或预览当前 Craft ${label} 游戏 ${name};新会话恢复项目进度、引擎上下文和预览状态时使用。Continue this existing Craft game; use craft-create only for a new game.\n---\n\n`
|
|
102
103
|
+ start + '\n# 继续当前 Craft 游戏\n\n'
|
|
103
104
|
+ `1. 读取项目根 \`AGENTS.md\`,确认工程 \`${name}\` 和引擎 \`${engine}\`。\n`
|
|
104
|
-
+ (isolated ? '2. 新会话先调用只读 `craft_game_info` 核对项目,再调用 `craft_update_check`(name、
|
|
105
|
-
+ (isolated
|
|
106
|
-
+ (isolated
|
|
107
|
-
+ (isolated && ['codex','workbuddy'].includes(host) ? ' 重连后通过当前聊天的 craft_game_info 核对实际版本和 build_id 与目标一致,记录实际 instance_id,确认 active_verified 且 host/workspace/platform 符合预期,不能仅凭绿灯或重载成功继续;只重试明确未开始的 prepare 并复用 request_key,不重放付费操作。\n' : '')
|
|
105
|
+
+ (isolated ? '2. 新会话先调用只读 `craft_game_info` 核对项目,再调用 `craft_update_check`(name、本次 request_key)检查版本,不写文件。继续制作且发现可用新版、自动更新已启用时,调用 `craft_update`(name、mode=auto、同一 request_key)安装;新版下次启动或用户重连生效,核对实际版本后,等待可继续后调用 `craft_game_prepare`(mode=resume,同一 request_key)。轮询完成并保留 work_id/context_revision,重新读取本 Skill 相邻的 [引擎入口](../../AGENTS.md)、[恢复说明](../../recovery.md)、[工作流](../../workflow.md) 和 [技能索引](../index.json),按任务读取当前宿主 skills/ 下的正文。\n' : '2. 按根 AGENTS.md 查询 `craft_game_info`,读取返回的引擎入口、工作流与技能索引。\n')
|
|
106
|
+
+ (isolated ? ' 新版安装后等待下次 MCP 启动或用户重连。确认实际 version、build_id、active_verified 后,prepare(resume) 更新当前宿主、原引擎的上下文和 Skill,再重新读取正文。\n' : '')
|
|
107
|
+
+ (isolated ? ' 不主动重载或中断工作;按 connection_handoff 提示用户,先保存进度并 release。只重试明确未开始的 prepare,不重放结果不明的操作。\n' : '')
|
|
108
108
|
+ '3. 纯查看只读现有文件,不 prepare。制作工具带 work_id;完成修改后更新进度并按工作流验收、看图、启动预览。等待后台任务结束后调用 craft_game_release(name,work_id)。重试准备复用原 request_key,下一轮制作使用新 key;resume 不安装依赖或重建模板。\n'
|
|
109
109
|
+ end + '\n';
|
|
110
110
|
let hostEntry;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
|
+
import { createReadStream } from 'node:fs';
|
|
2
3
|
import { mkdir, readFile, writeFile, lstat, realpath, readdir } from 'node:fs/promises';
|
|
3
4
|
import { createHash } from 'node:crypto';
|
|
4
5
|
import { seedProjectTemplate } from '#craft-sdk';
|
|
@@ -162,7 +163,7 @@ export class Projects {
|
|
|
162
163
|
|
|
163
164
|
const skip = new Set(['node_modules','dist','.git','.visualqa','.cache','.vite','.turbo']);
|
|
164
165
|
export async function fingerprint(project) {
|
|
165
|
-
const hash = createHash('sha256'); let files = 0
|
|
166
|
+
const hash = createHash('sha256'); let files = 0;
|
|
166
167
|
async function walk(dir, relative) {
|
|
167
168
|
const entries = (await readdir(dir,{ withFileTypes:true })).sort((a,b)=>a.name.localeCompare(b.name));
|
|
168
169
|
for (const entry of entries) {
|
|
@@ -175,9 +176,10 @@ export async function fingerprint(project) {
|
|
|
175
176
|
if (!entry.isFile()) throw new Error('Unsupported source file: ' + key);
|
|
176
177
|
// Session handoff notes are not build inputs. Recording a check receipt must not invalidate that check.
|
|
177
178
|
if (key === '/SPEC/PROGRESS.md' || /^\/\.workbuddy\/memory\/.*\.md$/.test(key)) continue;
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
179
|
+
if (++files > 10000) throw new Error('Project exceeds source snapshot file count limit');
|
|
180
|
+
hash.update(key).update('\0');
|
|
181
|
+
for await (const chunk of createReadStream(file)) hash.update(chunk);
|
|
182
|
+
hash.update('\0');
|
|
181
183
|
}
|
|
182
184
|
}
|
|
183
185
|
await walk(project,'');
|
|
@@ -69,7 +69,7 @@ export class Tasks {
|
|
|
69
69
|
if (remote) { record.other_session = true; record.next = 'Task is running in another Craft session. Read progress here; cancel or continue it in its owning session.'; }
|
|
70
70
|
else {
|
|
71
71
|
record.status = 'interrupted';
|
|
72
|
-
record.next = record.kind === 'upload' ? 'Host stopped. Resume craft_game_upload with the same check_task_id.' :
|
|
72
|
+
record.next = record.kind === 'upload' ? 'Host stopped. Resume craft_game_upload with the same check_task_id, upload_mode and request_key.' :
|
|
73
73
|
'Host stopped. Prepare the same project and reuse the same asset request_key to resume; never invent a new key for a retry.';
|
|
74
74
|
}
|
|
75
75
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
-
|
|
3
|
-
// Carries logical ownership through async tools, background tasks
|
|
4
|
-
const storage=new AsyncLocalStorage();
|
|
5
|
-
export const currentWork=()=>storage.getStore()?.work;
|
|
6
|
-
export const withWork=(work,validate,operation)=>storage.run({work,validate},operation);
|
|
7
|
-
export async function guardWork() { await storage.getStore()?.validate?.(); }
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
|
|
3
|
+
// Carries logical ownership through async tools, background tasks.
|
|
4
|
+
const storage=new AsyncLocalStorage();
|
|
5
|
+
export const currentWork=()=>storage.getStore()?.work;
|
|
6
|
+
export const withWork=(work,validate,operation)=>storage.run({work,validate},operation);
|
|
7
|
+
export async function guardWork() { await storage.getStore()?.validate?.(); }
|