@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,289 +1,289 @@
|
|
|
1
|
-
import path from 'node:path';
|
|
2
|
-
import { cp, mkdir, readFile, readdir, writeFile, lstat, rename, rm, open } from 'node:fs/promises';
|
|
3
|
-
import { randomUUID } from 'node:crypto';
|
|
4
|
-
import { isDeepStrictEqual } from 'node:util';
|
|
5
|
-
import { safeProjectFile } from './asset-import.mjs';
|
|
6
|
-
import { digest } from './bundle-files.mjs';
|
|
7
|
-
import { hosts } from '../integrations/hosts.mjs';
|
|
8
|
-
import { atomicJson } from './request-store.mjs';
|
|
9
|
-
|
|
10
|
-
export const contextLayoutSchema = 5;
|
|
11
|
-
// Schema 4 used one physical Buddy directory. Never validate a historical lock
|
|
12
|
-
// with today's host map: doing so would make valid projects impossible to migrate.
|
|
13
|
-
const schema4Paths = Object.freeze({codex:'.agents',cursor:'.cursor',workbuddy:'.codebuddy',codebuddy:'.codebuddy'});
|
|
14
|
-
export const schema4Hosts = Object.freeze(Object.keys(schema4Paths));
|
|
15
|
-
// New hosts have no historical directory; read-only inspection reports their
|
|
16
|
-
// intended directory as missing until prepare attaches them.
|
|
17
|
-
export const nativeContextPath = (host, schema = contextLayoutSchema) => schema === 4 && Object.hasOwn(schema4Paths,host)
|
|
18
|
-
? schema4Paths[host] : path.posix.dirname(hosts[host].projectSkills);
|
|
19
|
-
const manifestName = 'craft-context.json';
|
|
20
|
-
async function directory(project,relative) {
|
|
21
|
-
const parts=relative.split('/');
|
|
22
|
-
if(parts.some(p=>!p||p==='.'||p==='..'||p.includes('\\'))) throw new Error('Invalid context directory');
|
|
23
|
-
const parent=parts.slice(0,-1).join('/');
|
|
24
|
-
await safeProjectFile(project,(parent ? parent+'/' : '')+'.directory-check',true);
|
|
25
|
-
const target=path.join(project,...parts);
|
|
26
|
-
try {const stat=await lstat(target); if(!stat.isDirectory()||stat.isSymbolicLink()) throw new Error('Context path contains a link or invalid directory');}
|
|
27
|
-
catch(error) {if(error.code!=='ENOENT') throw error;}
|
|
28
|
-
return target;
|
|
29
|
-
}
|
|
30
|
-
async function optional(file) {
|
|
31
|
-
try {return await readFile(file);} catch(error) {if(error.code==='ENOENT') return null; throw error;}
|
|
32
|
-
}
|
|
33
|
-
async function hashes(root,relative='') {
|
|
34
|
-
const result={};
|
|
35
|
-
for(const entry of (await readdir(path.join(root,relative),{withFileTypes:true})).sort((a,b)=>a.name.localeCompare(b.name))) {
|
|
36
|
-
if(entry.isSymbolicLink() || (!entry.isDirectory() && !entry.isFile())) throw new Error('Project context contains a link or special file');
|
|
37
|
-
const name=relative ? relative+'/'+entry.name : entry.name;
|
|
38
|
-
if(entry.isDirectory()) Object.assign(result,await hashes(root,name));
|
|
39
|
-
else result[name]=digest(await readFile(path.join(root,name)));
|
|
40
|
-
}
|
|
41
|
-
return result;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// Preserve relative paths used by knowledge links, executable skills and SDK hooks.
|
|
45
|
-
export function nativeContextFile(name,engine) {
|
|
46
|
-
if(name.startsWith(engine+'/context/')) return name.slice((engine+'/context/').length);
|
|
47
|
-
if(name==='craft-game-maker/SKILL.md') return 'workflow.md';
|
|
48
|
-
if(name===`craft-game-maker/${engine}.md`) return 'guide.md';
|
|
49
|
-
if(name==='bootstrap/SKILL.md') return 'create.md';
|
|
50
|
-
if(name.startsWith('bootstrap/')) return 'creation/'+name.slice(10);
|
|
51
|
-
if(['recovery.md','target.json'].includes(name)) return name;
|
|
52
|
-
return null;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export function nativeSelection(project,current,{schema=contextLayoutSchema}={}) {
|
|
56
|
-
const target=path.join(project,nativeContextPath(current.host,schema));
|
|
57
|
-
return {...current,resources:target,template:undefined,context:{...current.context,
|
|
58
|
-
workflow:path.join(target,'workflow.md'),recovery:path.join(target,'recovery.md'),
|
|
59
|
-
engine:{...current.context.engine,directory:target,guide:path.join(target,'guide.md'),entrypoint:path.join(target,'AGENTS.md'),skills_index:path.join(target,'skills/index.json')},
|
|
60
|
-
references:Object.fromEntries(Object.entries(current.context.references).map(([key,file])=>[key,path.join(target,path.relative(current.context.engine.directory,file))]))}};
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// Inspection never creates directories, repairs content, or acquires a write lease.
|
|
64
|
-
export async function inspectNativeContext(project,host,engine,{full=false,schema=contextLayoutSchema}={}) {
|
|
65
|
-
const relative=nativeContextPath(host,schema);
|
|
66
|
-
try {
|
|
67
|
-
const manifest=JSON.parse(await readFile(await safeProjectFile(project,relative+'/'+manifestName),'utf8'));
|
|
68
|
-
if(manifest.schema!==1 || manifest.host!==host || manifest.engine!==engine || !/^[a-f0-9]{64}$/.test(manifest.bundle_id) ||
|
|
69
|
-
!/^\d+\.\d+\.\d+$/.test(manifest.version??'') || typeof manifest.source_revision!=='string' || !manifest.source_revision ||
|
|
70
|
-
!validFileMap(manifest.files) || !Object.keys(manifest.files).length) throw new Error('Native context identity mismatch');
|
|
71
|
-
if(full) for(const [name,hash] of Object.entries(manifest.files)) {
|
|
72
|
-
if(!/^[a-f0-9]{64}$/.test(hash)) throw new Error('Invalid native context checksum');
|
|
73
|
-
if(digest(await readFile(await safeProjectFile(project,relative+'/'+name)))!==hash) return {manifest,integrity:'modified',reason:relative+'/'+name};
|
|
74
|
-
}
|
|
75
|
-
return {manifest,integrity:full ? 'valid' : 'unchecked'};
|
|
76
|
-
} catch(error) {return {integrity:'invalid',reason:error.message};}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export async function resolveNativeContext(project,current,lock) {
|
|
80
|
-
const binding=lock?.contexts?.[current.host];
|
|
81
|
-
if(lock?.schema!==contextLayoutSchema || binding?.bundle_id!==current.bundle.id || lock.active_hosts?.[nativeContextPath(current.host)]!==current.host) throw new Error('Project context requires preparation with the installed host runtime; run craft_game_prepare mode=resume');
|
|
82
|
-
const checked=await inspectNativeContext(project,current.host,current.engine,{full:true});
|
|
83
|
-
const expected=Object.fromEntries(Object.entries(current.bundle.files).flatMap(([name,hash])=>{
|
|
84
|
-
const file=nativeContextFile(name,current.engine); return file ? [[file,hash]] : [];
|
|
85
|
-
}));
|
|
86
|
-
if(checked.integrity!=='valid' || checked.manifest.bundle_id!==binding.bundle_id || checked.manifest.source_revision!==binding.source_revision || !isDeepStrictEqual(checked.manifest.files,expected)) throw new Error('Project context integrity check failed: '+(checked.reason??'binding or manifest mismatch')+'; run craft_game_prepare mode=resume');
|
|
87
|
-
const selected=nativeSelection(project,current);
|
|
88
|
-
selected.context.hosts=Object.fromEntries(Object.entries(lock.active_hosts).map(([directory,host])=>[host,path.join(project,directory)]));
|
|
89
|
-
selected.context.user_rules=path.join(project,'.craft/user-rules.md');
|
|
90
|
-
return selected;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
function validFileMap(value) {
|
|
94
|
-
return value && typeof value==='object' && !Array.isArray(value) && Object.entries(value).every(([name,hash])=>
|
|
95
|
-
typeof hash==='string' && /^[a-f0-9]{64}$/.test(hash) && name && !path.isAbsolute(name) &&
|
|
96
|
-
!name.includes('\\') && !name.includes(':') && name.split('/').every(part=>part && part!=='.' && part!=='..'));
|
|
97
|
-
}
|
|
98
|
-
async function fileHash(project,name) {
|
|
99
|
-
try {const bytes=await optional(await safeProjectFile(project,name)); return bytes===null ? null : digest(bytes);}
|
|
100
|
-
catch(error) {if(error.code==='ENOENT') return null; throw error;}
|
|
101
|
-
}
|
|
102
|
-
const expectedHash=(files,name)=>Object.hasOwn(files,name) ? files[name] : null;
|
|
103
|
-
|
|
104
|
-
// Keep discovery directories (including skills/) in place: an active Windows host
|
|
105
|
-
// can hold a descendant directory handle even when individual files are writable.
|
|
106
|
-
// The project preparation marker prevents consumers from treating a partial batch
|
|
107
|
-
// as ready. The durable journal permits roll-forward after any file operation.
|
|
108
|
-
async function publishFiles(project,job,guard) {
|
|
109
|
-
if(!validFileMap(job.before) || !validFileMap(job.after) || !job.after[manifestName]) throw new Error('Invalid native file transaction');
|
|
110
|
-
const target=await directory(project,job.target), staging=await directory(project,job.staging), backup=await directory(project,job.backup);
|
|
111
|
-
const staged=await hashes(staging), saved=await hashes(backup);
|
|
112
|
-
const names=[...new Set([...Object.keys(job.before),...Object.keys(job.after)])].sort((a,b)=>
|
|
113
|
-
a===manifestName ? 1 : b===manifestName ? -1 : a.localeCompare(b));
|
|
114
|
-
for(const name of names) {
|
|
115
|
-
if(expectedHash(staged,name)!==expectedHash(job.after,name) || expectedHash(saved,name)!==expectedHash(job.before,name)) throw new Error('Native context transaction snapshot integrity failed');
|
|
116
|
-
const actual=await fileHash(project,job.target+'/'+name);
|
|
117
|
-
if(actual!==expectedHash(job.before,name) && actual!==expectedHash(job.after,name)) throw new Error('Project host file changed during context publication: '+job.target+'/'+name);
|
|
118
|
-
}
|
|
119
|
-
const token=path.posix.basename(job.staging);
|
|
120
|
-
await guard(); await mkdir(target,{recursive:true});
|
|
121
|
-
for(const name of names) {
|
|
122
|
-
const before=expectedHash(job.before,name), after=expectedHash(job.after,name);
|
|
123
|
-
await guard();
|
|
124
|
-
const actual=await fileHash(project,job.target+'/'+name);
|
|
125
|
-
if(actual!==before && actual!==after) throw new Error('Project host file changed during context publication: '+job.target+'/'+name);
|
|
126
|
-
if(before===after) continue;
|
|
127
|
-
// Temporary files inherit the destination directory's permissions. Never
|
|
128
|
-
// rewrite a locked file in place or change ACLs to bypass an access failure.
|
|
129
|
-
const temporaryRelative=job.target+'/'+name+'.craft-'+token+'.tmp';
|
|
130
|
-
let temporaryHash=await fileHash(project,temporaryRelative);
|
|
131
|
-
// A killed process may leave an incomplete private temporary file. The
|
|
132
|
-
// validated staged copy remains authoritative; the destination is untouched.
|
|
133
|
-
if(temporaryHash!==null && temporaryHash!==after) {
|
|
134
|
-
if(after===null) throw new Error('Unexpected native context temporary file');
|
|
135
|
-
await rm(await safeProjectFile(project,temporaryRelative)); temporaryHash=null;
|
|
136
|
-
}
|
|
137
|
-
if(actual===after) {
|
|
138
|
-
if(temporaryHash!==null) await rm(await safeProjectFile(project,temporaryRelative));
|
|
139
|
-
continue;
|
|
140
|
-
}
|
|
141
|
-
const destination=await safeProjectFile(project,job.target+'/'+name,after!==null);
|
|
142
|
-
if(after===null) {await rm(destination); continue;}
|
|
143
|
-
const temporary=await safeProjectFile(project,temporaryRelative,true);
|
|
144
|
-
if(temporaryHash===null) {
|
|
145
|
-
const bytes=await readFile(await safeProjectFile(project,job.staging+'/'+name));
|
|
146
|
-
if(digest(bytes)!==after) throw new Error('Native context staged file changed');
|
|
147
|
-
const handle=await open(temporary,'wx');
|
|
148
|
-
try {await handle.writeFile(bytes); await handle.sync();} finally {await handle.close();}
|
|
149
|
-
}
|
|
150
|
-
await guard();
|
|
151
|
-
if(await fileHash(project,job.target+'/'+name)!==before) throw new Error('Project host file changed during context publication: '+job.target+'/'+name);
|
|
152
|
-
await rename(temporary,destination);
|
|
153
|
-
}
|
|
154
|
-
for(const name of names) if(await fileHash(project,job.target+'/'+name)!==expectedHash(job.after,name)) throw new Error('Native context publication integrity failed');
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
// Also recover the directory-swap journal written by releases through 0.1.33.
|
|
158
|
-
export async function recoverNativeContext(project,host,guard=async()=>{}) {
|
|
159
|
-
return recoverNativeContextAt(project,nativeContextPath(host),guard);
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
// Called before a legacy layout migration. A pending transaction belongs to
|
|
163
|
-
// its recorded physical directory, even after the host's canonical path changes.
|
|
164
|
-
export async function recoverLegacyNativeContexts(project,lock,guard=async()=>{}) {
|
|
165
|
-
if(!lock || lock.schema>=contextLayoutSchema) return;
|
|
166
|
-
for(const relative of new Set(Object.values(schema4Paths))) await recoverNativeContextAt(project,relative,guard);
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
async function recoverNativeContextAt(project,relative,guard) {
|
|
170
|
-
const slot=relative.slice(1);
|
|
171
|
-
const journalFile=await safeProjectFile(project,`.craft/context-transactions/${slot}.json`,true);
|
|
172
|
-
const raw=await optional(journalFile);
|
|
173
|
-
if(!raw) return;
|
|
174
|
-
const job=JSON.parse(raw);
|
|
175
|
-
if(job.target!==relative || !/^\.craft\/context-staging\/[a-f0-9-]{36}$/.test(job.staging) ||
|
|
176
|
-
!/^\.craft\/context-backups\/[a-z]+\/[a-f0-9-]{36}$/.test(job.backup) || !/^[a-f0-9]{64}$/.test(job.bundle)) throw new Error('Invalid native context transaction');
|
|
177
|
-
if(job.schema===2) {
|
|
178
|
-
await publishFiles(project,job,guard);
|
|
179
|
-
await guard(); await rm(journalFile);
|
|
180
|
-
await rm(await directory(project,job.staging),{recursive:true,force:true});
|
|
181
|
-
return {backup:path.join(project,job.backup)};
|
|
182
|
-
}
|
|
183
|
-
if(job.schema!==undefined) throw new Error('Unsupported native context transaction');
|
|
184
|
-
await guard();
|
|
185
|
-
const target=await directory(project,job.target), staging=await directory(project,job.staging), backup=await directory(project,job.backup);
|
|
186
|
-
const present=await optional(path.join(target,manifestName));
|
|
187
|
-
if(!(present && JSON.parse(present).bundle_id===job.bundle)) {
|
|
188
|
-
let exists=false;
|
|
189
|
-
try {await lstat(target); exists=true;} catch(error) {if(error.code!=='ENOENT') throw error;}
|
|
190
|
-
if(!exists) {
|
|
191
|
-
try {await lstat(backup); await rename(backup,target);} catch(error) {if(error.code!=='ENOENT') throw error;}
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
await rm(staging,{recursive:true,force:true});
|
|
195
|
-
await rm(journalFile);
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
// Check every planned host before publishing the first one. A user-owned file
|
|
199
|
-
// collision must not leave unrelated newly-created host surfaces behind.
|
|
200
|
-
export async function preflightNativeContext(project,current,{legacyBinding}={}) {
|
|
201
|
-
const {host,engine,bundle}=current, relative=nativeContextPath(host), target=await directory(project,relative);
|
|
202
|
-
const raw=await optional(path.join(target,manifestName)), owned=raw ? JSON.parse(raw) : null;
|
|
203
|
-
const legacyOwner=relative==='.codebuddy' && host==='codebuddy' && owned?.host==='workbuddy' && legacyBinding &&
|
|
204
|
-
owned.bundle_id===legacyBinding.bundle_id && owned.source_revision===legacyBinding.source_revision && owned.version===legacyBinding.version;
|
|
205
|
-
if(owned && (owned.schema!==1 || !hosts[owned.host] || (nativeContextPath(owned.host)!==relative && !legacyOwner) || owned.engine!==engine ||
|
|
206
|
-
!/^[a-f0-9]{64}$/.test(owned.bundle_id) || !/^\d+\.\d+\.\d+$/.test(owned.version??'') || !validFileMap(owned.files))) throw new Error('Invalid native context manifest');
|
|
207
|
-
if(owned?.host===host && owned.bundle_id!==bundle.id) {
|
|
208
|
-
const difference=bundle.version.split('.').map((n,i)=>Number(n)-Number(owned.version.split('.')[i])).find(n=>n!==0)??0;
|
|
209
|
-
if(difference<=0) throw new Error('Installed context is older or has a conflicting version with the published native context');
|
|
210
|
-
}
|
|
211
|
-
for(const name of Object.keys(bundle.files)) {
|
|
212
|
-
const output=nativeContextFile(name,engine);
|
|
213
|
-
if(output && !owned?.files[output] && await fileHash(project,relative+'/'+output)!==null) throw new Error('Unmanaged project context file at '+relative+'/'+output+'; preserve or relocate it before retrying');
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
export async function materializeNativeContext(project,current,guard=async()=>{}, {legacyBinding}={}) {
|
|
218
|
-
const {host,engine,bundle,resources}=current, relative=nativeContextPath(host);
|
|
219
|
-
const recovered=await recoverNativeContext(project,host,guard);
|
|
220
|
-
const target=await directory(project,relative);
|
|
221
|
-
let present=false, before={};
|
|
222
|
-
try {
|
|
223
|
-
const stat=await lstat(target);
|
|
224
|
-
if(!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Project context target must be a regular directory');
|
|
225
|
-
present=true; before=await hashes(target);
|
|
226
|
-
} catch(error) {if(error.code!=='ENOENT') throw error;}
|
|
227
|
-
const raw=present ? await optional(path.join(target,manifestName)) : null;
|
|
228
|
-
const owned=raw ? JSON.parse(raw) : null;
|
|
229
|
-
const legacyOwner=relative==='.codebuddy' && host==='codebuddy' && owned?.host==='workbuddy' && legacyBinding &&
|
|
230
|
-
owned.bundle_id===legacyBinding.bundle_id && owned.source_revision===legacyBinding.source_revision && owned.version===legacyBinding.version;
|
|
231
|
-
if(owned && (owned.schema!==1 || !hosts[owned.host] || (nativeContextPath(owned.host)!==relative && !legacyOwner) || owned.engine!==engine ||
|
|
232
|
-
!/^[a-f0-9]{64}$/.test(owned.bundle_id) || !/^\d+\.\d+\.\d+$/.test(owned.version??'') || !validFileMap(owned.files))) throw new Error('Invalid native context manifest');
|
|
233
|
-
if(owned?.host===host && owned.bundle_id!==bundle.id) {
|
|
234
|
-
const difference=bundle.version.split('.').map((n,i)=>Number(n)-Number(owned.version.split('.')[i])).find(n=>n!==0)??0;
|
|
235
|
-
if(difference<=0) throw new Error('Installed context is older or has a conflicting version with the published native context');
|
|
236
|
-
}
|
|
237
|
-
const files={}, payload=new Map();
|
|
238
|
-
for(const name of Object.keys(bundle.files)) {
|
|
239
|
-
const output=nativeContextFile(name,engine);
|
|
240
|
-
if(!output) continue;
|
|
241
|
-
if(payload.has(output)) throw new Error('Duplicate native context destination');
|
|
242
|
-
const bytes=await readFile(path.join(resources,name));
|
|
243
|
-
payload.set(output,bytes); files[output]=digest(bytes);
|
|
244
|
-
}
|
|
245
|
-
const manifest={schema:1,host,engine,version:bundle.version,bundle_id:bundle.id,source_revision:bundle.source_revision,files};
|
|
246
|
-
const manifestBytes=Buffer.from(JSON.stringify(manifest,null,2)+'\n');
|
|
247
|
-
for(const name of payload.keys()) if(before[name] && !owned?.files[name]) throw new Error('Unmanaged project context file at '+relative+'/'+name+'; preserve or relocate it before retrying');
|
|
248
|
-
const complete=owned && isDeepStrictEqual(owned,manifest) && Object.entries(files).every(([name,hash])=>before[name]===hash);
|
|
249
|
-
const selected=nativeSelection(project,current);
|
|
250
|
-
if(complete) return {selected,relative,materialized:!!recovered,...recovered};
|
|
251
|
-
const token=randomUUID(), stagingRelative='.craft/context-staging/'+token, backupRelative='.craft/context-backups/'+host+'/'+token;
|
|
252
|
-
const staging=await directory(project,stagingRelative), backup=await directory(project,backupRelative);
|
|
253
|
-
await mkdir(staging);
|
|
254
|
-
const journalFile=await safeProjectFile(project,`.craft/context-transactions/${relative.slice(1)}.json`,true);
|
|
255
|
-
let journaled=false;
|
|
256
|
-
try {
|
|
257
|
-
if(present) await cp(target,staging,{recursive:true,errorOnExist:false});
|
|
258
|
-
for(const name of Object.keys(owned?.files??{})) if(!payload.has(name)) await rm(await safeProjectFile(staging,name),{force:true});
|
|
259
|
-
for(const [name,bytes] of payload) await writeFile(await safeProjectFile(staging,name,true),bytes);
|
|
260
|
-
await writeFile(await safeProjectFile(staging,manifestName,true),manifestBytes);
|
|
261
|
-
const staged=await hashes(staging);
|
|
262
|
-
if(!Object.entries(files).every(([name,hash])=>staged[name]===hash)) throw new Error('Native context staging integrity failed');
|
|
263
|
-
if(present && !isDeepStrictEqual(before,await hashes(target))) throw new Error('Project host files changed during context sync');
|
|
264
|
-
await guard();
|
|
265
|
-
if(present) await cp(target,backup,{recursive:true,preserveTimestamps:true});
|
|
266
|
-
else await mkdir(backup);
|
|
267
|
-
if(!isDeepStrictEqual(before,await hashes(backup)) || (present && !isDeepStrictEqual(before,await hashes(target)))) throw new Error('Project host files changed during context backup');
|
|
268
|
-
const managed=new Set([...Object.keys(owned?.files??{}),...payload.keys(),manifestName]);
|
|
269
|
-
const job={schema:2,target:relative,staging:stagingRelative,backup:backupRelative,bundle:bundle.id,
|
|
270
|
-
before:Object.fromEntries(Object.entries(before).filter(([name])=>managed.has(name))),
|
|
271
|
-
after:{...files,[manifestName]:digest(manifestBytes)}};
|
|
272
|
-
await guard(); await atomicJson(journalFile,job); journaled=true;
|
|
273
|
-
await publishFiles(project,job,guard);
|
|
274
|
-
await rm(journalFile);
|
|
275
|
-
journaled=false;
|
|
276
|
-
return {selected,relative,materialized:true,...(present ? {backup} : {})};
|
|
277
|
-
} finally {if(!journaled) await rm(staging,{recursive:true,force:true});}
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
export async function retireLegacyContext(project,host,engine,id) {
|
|
281
|
-
if(!hosts[host] || !['js','js3d'].includes(engine) || !/^[a-f0-9]{64}$/.test(id)) throw new Error('Invalid legacy context identity');
|
|
282
|
-
const relative=`.craft/contexts/${host}/${engine}/${id}`;
|
|
283
|
-
// Probe without creating old directories, then validate every component before moving.
|
|
284
|
-
try {await lstat(path.join(project,relative));} catch(error) {if(error.code==='ENOENT') return; throw error;}
|
|
285
|
-
const source=await directory(project,relative); await hashes(source);
|
|
286
|
-
const backup=await directory(project,`.craft/context-backups/${host}/${randomUUID()}`);
|
|
287
|
-
await rename(source,backup);
|
|
288
|
-
return backup;
|
|
289
|
-
}
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { cp, mkdir, readFile, readdir, writeFile, lstat, rename, rm, open } from 'node:fs/promises';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
5
|
+
import { safeProjectFile } from './asset-import.mjs';
|
|
6
|
+
import { digest } from './bundle-files.mjs';
|
|
7
|
+
import { hosts } from '../integrations/hosts.mjs';
|
|
8
|
+
import { atomicJson } from './request-store.mjs';
|
|
9
|
+
|
|
10
|
+
export const contextLayoutSchema = 5;
|
|
11
|
+
// Schema 4 used one physical Buddy directory. Never validate a historical lock
|
|
12
|
+
// with today's host map: doing so would make valid projects impossible to migrate.
|
|
13
|
+
const schema4Paths = Object.freeze({codex:'.agents',cursor:'.cursor',workbuddy:'.codebuddy',codebuddy:'.codebuddy'});
|
|
14
|
+
export const schema4Hosts = Object.freeze(Object.keys(schema4Paths));
|
|
15
|
+
// New hosts have no historical directory; read-only inspection reports their
|
|
16
|
+
// intended directory as missing until prepare attaches them.
|
|
17
|
+
export const nativeContextPath = (host, schema = contextLayoutSchema) => schema === 4 && Object.hasOwn(schema4Paths,host)
|
|
18
|
+
? schema4Paths[host] : path.posix.dirname(hosts[host].projectSkills);
|
|
19
|
+
const manifestName = 'craft-context.json';
|
|
20
|
+
async function directory(project,relative) {
|
|
21
|
+
const parts=relative.split('/');
|
|
22
|
+
if(parts.some(p=>!p||p==='.'||p==='..'||p.includes('\\'))) throw new Error('Invalid context directory');
|
|
23
|
+
const parent=parts.slice(0,-1).join('/');
|
|
24
|
+
await safeProjectFile(project,(parent ? parent+'/' : '')+'.directory-check',true);
|
|
25
|
+
const target=path.join(project,...parts);
|
|
26
|
+
try {const stat=await lstat(target); if(!stat.isDirectory()||stat.isSymbolicLink()) throw new Error('Context path contains a link or invalid directory');}
|
|
27
|
+
catch(error) {if(error.code!=='ENOENT') throw error;}
|
|
28
|
+
return target;
|
|
29
|
+
}
|
|
30
|
+
async function optional(file) {
|
|
31
|
+
try {return await readFile(file);} catch(error) {if(error.code==='ENOENT') return null; throw error;}
|
|
32
|
+
}
|
|
33
|
+
async function hashes(root,relative='') {
|
|
34
|
+
const result={};
|
|
35
|
+
for(const entry of (await readdir(path.join(root,relative),{withFileTypes:true})).sort((a,b)=>a.name.localeCompare(b.name))) {
|
|
36
|
+
if(entry.isSymbolicLink() || (!entry.isDirectory() && !entry.isFile())) throw new Error('Project context contains a link or special file');
|
|
37
|
+
const name=relative ? relative+'/'+entry.name : entry.name;
|
|
38
|
+
if(entry.isDirectory()) Object.assign(result,await hashes(root,name));
|
|
39
|
+
else result[name]=digest(await readFile(path.join(root,name)));
|
|
40
|
+
}
|
|
41
|
+
return result;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Preserve relative paths used by knowledge links, executable skills and SDK hooks.
|
|
45
|
+
export function nativeContextFile(name,engine) {
|
|
46
|
+
if(name.startsWith(engine+'/context/')) return name.slice((engine+'/context/').length);
|
|
47
|
+
if(name==='craft-game-maker/SKILL.md') return 'workflow.md';
|
|
48
|
+
if(name===`craft-game-maker/${engine}.md`) return 'guide.md';
|
|
49
|
+
if(name==='bootstrap/SKILL.md') return 'create.md';
|
|
50
|
+
if(name.startsWith('bootstrap/')) return 'creation/'+name.slice(10);
|
|
51
|
+
if(['recovery.md','target.json'].includes(name)) return name;
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function nativeSelection(project,current,{schema=contextLayoutSchema}={}) {
|
|
56
|
+
const target=path.join(project,nativeContextPath(current.host,schema));
|
|
57
|
+
return {...current,resources:target,template:undefined,context:{...current.context,
|
|
58
|
+
workflow:path.join(target,'workflow.md'),recovery:path.join(target,'recovery.md'),
|
|
59
|
+
engine:{...current.context.engine,directory:target,guide:path.join(target,'guide.md'),entrypoint:path.join(target,'AGENTS.md'),skills_index:path.join(target,'skills/index.json')},
|
|
60
|
+
references:Object.fromEntries(Object.entries(current.context.references).map(([key,file])=>[key,path.join(target,path.relative(current.context.engine.directory,file))]))}};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Inspection never creates directories, repairs content, or acquires a write lease.
|
|
64
|
+
export async function inspectNativeContext(project,host,engine,{full=false,schema=contextLayoutSchema}={}) {
|
|
65
|
+
const relative=nativeContextPath(host,schema);
|
|
66
|
+
try {
|
|
67
|
+
const manifest=JSON.parse(await readFile(await safeProjectFile(project,relative+'/'+manifestName),'utf8'));
|
|
68
|
+
if(manifest.schema!==1 || manifest.host!==host || manifest.engine!==engine || !/^[a-f0-9]{64}$/.test(manifest.bundle_id) ||
|
|
69
|
+
!/^\d+\.\d+\.\d+$/.test(manifest.version??'') || typeof manifest.source_revision!=='string' || !manifest.source_revision ||
|
|
70
|
+
!validFileMap(manifest.files) || !Object.keys(manifest.files).length) throw new Error('Native context identity mismatch');
|
|
71
|
+
if(full) for(const [name,hash] of Object.entries(manifest.files)) {
|
|
72
|
+
if(!/^[a-f0-9]{64}$/.test(hash)) throw new Error('Invalid native context checksum');
|
|
73
|
+
if(digest(await readFile(await safeProjectFile(project,relative+'/'+name)))!==hash) return {manifest,integrity:'modified',reason:relative+'/'+name};
|
|
74
|
+
}
|
|
75
|
+
return {manifest,integrity:full ? 'valid' : 'unchecked'};
|
|
76
|
+
} catch(error) {return {integrity:'invalid',reason:error.message};}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function resolveNativeContext(project,current,lock) {
|
|
80
|
+
const binding=lock?.contexts?.[current.host];
|
|
81
|
+
if(lock?.schema!==contextLayoutSchema || binding?.bundle_id!==current.bundle.id || lock.active_hosts?.[nativeContextPath(current.host)]!==current.host) throw new Error('Project context requires preparation with the installed host runtime; run craft_game_prepare mode=resume');
|
|
82
|
+
const checked=await inspectNativeContext(project,current.host,current.engine,{full:true});
|
|
83
|
+
const expected=Object.fromEntries(Object.entries(current.bundle.files).flatMap(([name,hash])=>{
|
|
84
|
+
const file=nativeContextFile(name,current.engine); return file ? [[file,hash]] : [];
|
|
85
|
+
}));
|
|
86
|
+
if(checked.integrity!=='valid' || checked.manifest.bundle_id!==binding.bundle_id || checked.manifest.source_revision!==binding.source_revision || !isDeepStrictEqual(checked.manifest.files,expected)) throw new Error('Project context integrity check failed: '+(checked.reason??'binding or manifest mismatch')+'; run craft_game_prepare mode=resume');
|
|
87
|
+
const selected=nativeSelection(project,current);
|
|
88
|
+
selected.context.hosts=Object.fromEntries(Object.entries(lock.active_hosts).map(([directory,host])=>[host,path.join(project,directory)]));
|
|
89
|
+
selected.context.user_rules=path.join(project,'.craft/user-rules.md');
|
|
90
|
+
return selected;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function validFileMap(value) {
|
|
94
|
+
return value && typeof value==='object' && !Array.isArray(value) && Object.entries(value).every(([name,hash])=>
|
|
95
|
+
typeof hash==='string' && /^[a-f0-9]{64}$/.test(hash) && name && !path.isAbsolute(name) &&
|
|
96
|
+
!name.includes('\\') && !name.includes(':') && name.split('/').every(part=>part && part!=='.' && part!=='..'));
|
|
97
|
+
}
|
|
98
|
+
async function fileHash(project,name) {
|
|
99
|
+
try {const bytes=await optional(await safeProjectFile(project,name)); return bytes===null ? null : digest(bytes);}
|
|
100
|
+
catch(error) {if(error.code==='ENOENT') return null; throw error;}
|
|
101
|
+
}
|
|
102
|
+
const expectedHash=(files,name)=>Object.hasOwn(files,name) ? files[name] : null;
|
|
103
|
+
|
|
104
|
+
// Keep discovery directories (including skills/) in place: an active Windows host
|
|
105
|
+
// can hold a descendant directory handle even when individual files are writable.
|
|
106
|
+
// The project preparation marker prevents consumers from treating a partial batch
|
|
107
|
+
// as ready. The durable journal permits roll-forward after any file operation.
|
|
108
|
+
async function publishFiles(project,job,guard) {
|
|
109
|
+
if(!validFileMap(job.before) || !validFileMap(job.after) || !job.after[manifestName]) throw new Error('Invalid native file transaction');
|
|
110
|
+
const target=await directory(project,job.target), staging=await directory(project,job.staging), backup=await directory(project,job.backup);
|
|
111
|
+
const staged=await hashes(staging), saved=await hashes(backup);
|
|
112
|
+
const names=[...new Set([...Object.keys(job.before),...Object.keys(job.after)])].sort((a,b)=>
|
|
113
|
+
a===manifestName ? 1 : b===manifestName ? -1 : a.localeCompare(b));
|
|
114
|
+
for(const name of names) {
|
|
115
|
+
if(expectedHash(staged,name)!==expectedHash(job.after,name) || expectedHash(saved,name)!==expectedHash(job.before,name)) throw new Error('Native context transaction snapshot integrity failed');
|
|
116
|
+
const actual=await fileHash(project,job.target+'/'+name);
|
|
117
|
+
if(actual!==expectedHash(job.before,name) && actual!==expectedHash(job.after,name)) throw new Error('Project host file changed during context publication: '+job.target+'/'+name);
|
|
118
|
+
}
|
|
119
|
+
const token=path.posix.basename(job.staging);
|
|
120
|
+
await guard(); await mkdir(target,{recursive:true});
|
|
121
|
+
for(const name of names) {
|
|
122
|
+
const before=expectedHash(job.before,name), after=expectedHash(job.after,name);
|
|
123
|
+
await guard();
|
|
124
|
+
const actual=await fileHash(project,job.target+'/'+name);
|
|
125
|
+
if(actual!==before && actual!==after) throw new Error('Project host file changed during context publication: '+job.target+'/'+name);
|
|
126
|
+
if(before===after) continue;
|
|
127
|
+
// Temporary files inherit the destination directory's permissions. Never
|
|
128
|
+
// rewrite a locked file in place or change ACLs to bypass an access failure.
|
|
129
|
+
const temporaryRelative=job.target+'/'+name+'.craft-'+token+'.tmp';
|
|
130
|
+
let temporaryHash=await fileHash(project,temporaryRelative);
|
|
131
|
+
// A killed process may leave an incomplete private temporary file. The
|
|
132
|
+
// validated staged copy remains authoritative; the destination is untouched.
|
|
133
|
+
if(temporaryHash!==null && temporaryHash!==after) {
|
|
134
|
+
if(after===null) throw new Error('Unexpected native context temporary file');
|
|
135
|
+
await rm(await safeProjectFile(project,temporaryRelative)); temporaryHash=null;
|
|
136
|
+
}
|
|
137
|
+
if(actual===after) {
|
|
138
|
+
if(temporaryHash!==null) await rm(await safeProjectFile(project,temporaryRelative));
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
const destination=await safeProjectFile(project,job.target+'/'+name,after!==null);
|
|
142
|
+
if(after===null) {await rm(destination); continue;}
|
|
143
|
+
const temporary=await safeProjectFile(project,temporaryRelative,true);
|
|
144
|
+
if(temporaryHash===null) {
|
|
145
|
+
const bytes=await readFile(await safeProjectFile(project,job.staging+'/'+name));
|
|
146
|
+
if(digest(bytes)!==after) throw new Error('Native context staged file changed');
|
|
147
|
+
const handle=await open(temporary,'wx');
|
|
148
|
+
try {await handle.writeFile(bytes); await handle.sync();} finally {await handle.close();}
|
|
149
|
+
}
|
|
150
|
+
await guard();
|
|
151
|
+
if(await fileHash(project,job.target+'/'+name)!==before) throw new Error('Project host file changed during context publication: '+job.target+'/'+name);
|
|
152
|
+
await rename(temporary,destination);
|
|
153
|
+
}
|
|
154
|
+
for(const name of names) if(await fileHash(project,job.target+'/'+name)!==expectedHash(job.after,name)) throw new Error('Native context publication integrity failed');
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Also recover the directory-swap journal written by releases through 0.1.33.
|
|
158
|
+
export async function recoverNativeContext(project,host,guard=async()=>{}) {
|
|
159
|
+
return recoverNativeContextAt(project,nativeContextPath(host),guard);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Called before a legacy layout migration. A pending transaction belongs to
|
|
163
|
+
// its recorded physical directory, even after the host's canonical path changes.
|
|
164
|
+
export async function recoverLegacyNativeContexts(project,lock,guard=async()=>{}) {
|
|
165
|
+
if(!lock || lock.schema>=contextLayoutSchema) return;
|
|
166
|
+
for(const relative of new Set(Object.values(schema4Paths))) await recoverNativeContextAt(project,relative,guard);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function recoverNativeContextAt(project,relative,guard) {
|
|
170
|
+
const slot=relative.slice(1);
|
|
171
|
+
const journalFile=await safeProjectFile(project,`.craft/context-transactions/${slot}.json`,true);
|
|
172
|
+
const raw=await optional(journalFile);
|
|
173
|
+
if(!raw) return;
|
|
174
|
+
const job=JSON.parse(raw);
|
|
175
|
+
if(job.target!==relative || !/^\.craft\/context-staging\/[a-f0-9-]{36}$/.test(job.staging) ||
|
|
176
|
+
!/^\.craft\/context-backups\/[a-z]+\/[a-f0-9-]{36}$/.test(job.backup) || !/^[a-f0-9]{64}$/.test(job.bundle)) throw new Error('Invalid native context transaction');
|
|
177
|
+
if(job.schema===2) {
|
|
178
|
+
await publishFiles(project,job,guard);
|
|
179
|
+
await guard(); await rm(journalFile);
|
|
180
|
+
await rm(await directory(project,job.staging),{recursive:true,force:true});
|
|
181
|
+
return {backup:path.join(project,job.backup)};
|
|
182
|
+
}
|
|
183
|
+
if(job.schema!==undefined) throw new Error('Unsupported native context transaction');
|
|
184
|
+
await guard();
|
|
185
|
+
const target=await directory(project,job.target), staging=await directory(project,job.staging), backup=await directory(project,job.backup);
|
|
186
|
+
const present=await optional(path.join(target,manifestName));
|
|
187
|
+
if(!(present && JSON.parse(present).bundle_id===job.bundle)) {
|
|
188
|
+
let exists=false;
|
|
189
|
+
try {await lstat(target); exists=true;} catch(error) {if(error.code!=='ENOENT') throw error;}
|
|
190
|
+
if(!exists) {
|
|
191
|
+
try {await lstat(backup); await rename(backup,target);} catch(error) {if(error.code!=='ENOENT') throw error;}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
await rm(staging,{recursive:true,force:true});
|
|
195
|
+
await rm(journalFile);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// Check every planned host before publishing the first one. A user-owned file
|
|
199
|
+
// collision must not leave unrelated newly-created host surfaces behind.
|
|
200
|
+
export async function preflightNativeContext(project,current,{legacyBinding}={}) {
|
|
201
|
+
const {host,engine,bundle}=current, relative=nativeContextPath(host), target=await directory(project,relative);
|
|
202
|
+
const raw=await optional(path.join(target,manifestName)), owned=raw ? JSON.parse(raw) : null;
|
|
203
|
+
const legacyOwner=relative==='.codebuddy' && host==='codebuddy' && owned?.host==='workbuddy' && legacyBinding &&
|
|
204
|
+
owned.bundle_id===legacyBinding.bundle_id && owned.source_revision===legacyBinding.source_revision && owned.version===legacyBinding.version;
|
|
205
|
+
if(owned && (owned.schema!==1 || !hosts[owned.host] || (nativeContextPath(owned.host)!==relative && !legacyOwner) || owned.engine!==engine ||
|
|
206
|
+
!/^[a-f0-9]{64}$/.test(owned.bundle_id) || !/^\d+\.\d+\.\d+$/.test(owned.version??'') || !validFileMap(owned.files))) throw new Error('Invalid native context manifest');
|
|
207
|
+
if(owned?.host===host && owned.bundle_id!==bundle.id) {
|
|
208
|
+
const difference=bundle.version.split('.').map((n,i)=>Number(n)-Number(owned.version.split('.')[i])).find(n=>n!==0)??0;
|
|
209
|
+
if(difference<=0) throw new Error('Installed context is older or has a conflicting version with the published native context');
|
|
210
|
+
}
|
|
211
|
+
for(const name of Object.keys(bundle.files)) {
|
|
212
|
+
const output=nativeContextFile(name,engine);
|
|
213
|
+
if(output && !owned?.files[output] && await fileHash(project,relative+'/'+output)!==null) throw new Error('Unmanaged project context file at '+relative+'/'+output+'; preserve or relocate it before retrying');
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export async function materializeNativeContext(project,current,guard=async()=>{}, {legacyBinding}={}) {
|
|
218
|
+
const {host,engine,bundle,resources}=current, relative=nativeContextPath(host);
|
|
219
|
+
const recovered=await recoverNativeContext(project,host,guard);
|
|
220
|
+
const target=await directory(project,relative);
|
|
221
|
+
let present=false, before={};
|
|
222
|
+
try {
|
|
223
|
+
const stat=await lstat(target);
|
|
224
|
+
if(!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Project context target must be a regular directory');
|
|
225
|
+
present=true; before=await hashes(target);
|
|
226
|
+
} catch(error) {if(error.code!=='ENOENT') throw error;}
|
|
227
|
+
const raw=present ? await optional(path.join(target,manifestName)) : null;
|
|
228
|
+
const owned=raw ? JSON.parse(raw) : null;
|
|
229
|
+
const legacyOwner=relative==='.codebuddy' && host==='codebuddy' && owned?.host==='workbuddy' && legacyBinding &&
|
|
230
|
+
owned.bundle_id===legacyBinding.bundle_id && owned.source_revision===legacyBinding.source_revision && owned.version===legacyBinding.version;
|
|
231
|
+
if(owned && (owned.schema!==1 || !hosts[owned.host] || (nativeContextPath(owned.host)!==relative && !legacyOwner) || owned.engine!==engine ||
|
|
232
|
+
!/^[a-f0-9]{64}$/.test(owned.bundle_id) || !/^\d+\.\d+\.\d+$/.test(owned.version??'') || !validFileMap(owned.files))) throw new Error('Invalid native context manifest');
|
|
233
|
+
if(owned?.host===host && owned.bundle_id!==bundle.id) {
|
|
234
|
+
const difference=bundle.version.split('.').map((n,i)=>Number(n)-Number(owned.version.split('.')[i])).find(n=>n!==0)??0;
|
|
235
|
+
if(difference<=0) throw new Error('Installed context is older or has a conflicting version with the published native context');
|
|
236
|
+
}
|
|
237
|
+
const files={}, payload=new Map();
|
|
238
|
+
for(const name of Object.keys(bundle.files)) {
|
|
239
|
+
const output=nativeContextFile(name,engine);
|
|
240
|
+
if(!output) continue;
|
|
241
|
+
if(payload.has(output)) throw new Error('Duplicate native context destination');
|
|
242
|
+
const bytes=await readFile(path.join(resources,name));
|
|
243
|
+
payload.set(output,bytes); files[output]=digest(bytes);
|
|
244
|
+
}
|
|
245
|
+
const manifest={schema:1,host,engine,version:bundle.version,bundle_id:bundle.id,source_revision:bundle.source_revision,files};
|
|
246
|
+
const manifestBytes=Buffer.from(JSON.stringify(manifest,null,2)+'\n');
|
|
247
|
+
for(const name of payload.keys()) if(before[name] && !owned?.files[name]) throw new Error('Unmanaged project context file at '+relative+'/'+name+'; preserve or relocate it before retrying');
|
|
248
|
+
const complete=owned && isDeepStrictEqual(owned,manifest) && Object.entries(files).every(([name,hash])=>before[name]===hash);
|
|
249
|
+
const selected=nativeSelection(project,current);
|
|
250
|
+
if(complete) return {selected,relative,materialized:!!recovered,...recovered};
|
|
251
|
+
const token=randomUUID(), stagingRelative='.craft/context-staging/'+token, backupRelative='.craft/context-backups/'+host+'/'+token;
|
|
252
|
+
const staging=await directory(project,stagingRelative), backup=await directory(project,backupRelative);
|
|
253
|
+
await mkdir(staging);
|
|
254
|
+
const journalFile=await safeProjectFile(project,`.craft/context-transactions/${relative.slice(1)}.json`,true);
|
|
255
|
+
let journaled=false;
|
|
256
|
+
try {
|
|
257
|
+
if(present) await cp(target,staging,{recursive:true,errorOnExist:false});
|
|
258
|
+
for(const name of Object.keys(owned?.files??{})) if(!payload.has(name)) await rm(await safeProjectFile(staging,name),{force:true});
|
|
259
|
+
for(const [name,bytes] of payload) await writeFile(await safeProjectFile(staging,name,true),bytes);
|
|
260
|
+
await writeFile(await safeProjectFile(staging,manifestName,true),manifestBytes);
|
|
261
|
+
const staged=await hashes(staging);
|
|
262
|
+
if(!Object.entries(files).every(([name,hash])=>staged[name]===hash)) throw new Error('Native context staging integrity failed');
|
|
263
|
+
if(present && !isDeepStrictEqual(before,await hashes(target))) throw new Error('Project host files changed during context sync');
|
|
264
|
+
await guard();
|
|
265
|
+
if(present) await cp(target,backup,{recursive:true,preserveTimestamps:true});
|
|
266
|
+
else await mkdir(backup);
|
|
267
|
+
if(!isDeepStrictEqual(before,await hashes(backup)) || (present && !isDeepStrictEqual(before,await hashes(target)))) throw new Error('Project host files changed during context backup');
|
|
268
|
+
const managed=new Set([...Object.keys(owned?.files??{}),...payload.keys(),manifestName]);
|
|
269
|
+
const job={schema:2,target:relative,staging:stagingRelative,backup:backupRelative,bundle:bundle.id,
|
|
270
|
+
before:Object.fromEntries(Object.entries(before).filter(([name])=>managed.has(name))),
|
|
271
|
+
after:{...files,[manifestName]:digest(manifestBytes)}};
|
|
272
|
+
await guard(); await atomicJson(journalFile,job); journaled=true;
|
|
273
|
+
await publishFiles(project,job,guard);
|
|
274
|
+
await rm(journalFile);
|
|
275
|
+
journaled=false;
|
|
276
|
+
return {selected,relative,materialized:true,...(present ? {backup} : {})};
|
|
277
|
+
} finally {if(!journaled) await rm(staging,{recursive:true,force:true});}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export async function retireLegacyContext(project,host,engine,id) {
|
|
281
|
+
if(!hosts[host] || !['js','js3d'].includes(engine) || !/^[a-f0-9]{64}$/.test(id)) throw new Error('Invalid legacy context identity');
|
|
282
|
+
const relative=`.craft/contexts/${host}/${engine}/${id}`;
|
|
283
|
+
// Probe without creating old directories, then validate every component before moving.
|
|
284
|
+
try {await lstat(path.join(project,relative));} catch(error) {if(error.code==='ENOENT') return; throw error;}
|
|
285
|
+
const source=await directory(project,relative); await hashes(source);
|
|
286
|
+
const backup=await directory(project,`.craft/context-backups/${host}/${randomUUID()}`);
|
|
287
|
+
await rename(source,backup);
|
|
288
|
+
return backup;
|
|
289
|
+
}
|