@kevlns/art-workshop 0.4.2 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/AGENTS.md +25 -105
  2. package/LICENSE +21 -21
  3. package/README.md +63 -63
  4. package/art-workshop.mjs +174 -167
  5. package/docs/commands.md +116 -8
  6. package/docs/configuration.md +82 -82
  7. package/docs/core-guidance.md +50 -50
  8. package/docs/data-formats.md +85 -79
  9. package/docs/deployment.md +32 -32
  10. package/docs/local-models/qwen-image-2.1.json +73 -73
  11. package/docs/local-models/qwen-image-2.1.md +33 -33
  12. package/docs/model-architecture.md +78 -78
  13. package/docs/modes.md +67 -67
  14. package/lib/agent.mjs +32 -47
  15. package/lib/analysis-worker.mjs +32 -29
  16. package/lib/analyze.mjs +85 -78
  17. package/lib/asset-profile.mjs +23 -0
  18. package/lib/candidates.mjs +103 -101
  19. package/lib/comfy-recovery.mjs +17 -17
  20. package/lib/conversation.mjs +77 -0
  21. package/lib/core.mjs +75 -89
  22. package/lib/deployment-guide.mjs +12 -12
  23. package/lib/design.mjs +29 -29
  24. package/lib/dimensions.mjs +22 -22
  25. package/lib/edit.mjs +41 -38
  26. package/lib/environment-operations.mjs +49 -49
  27. package/lib/environment-runtime.mjs +99 -99
  28. package/lib/environments.mjs +55 -55
  29. package/lib/errors.mjs +32 -0
  30. package/lib/executor.mjs +107 -107
  31. package/lib/generate.mjs +58 -59
  32. package/lib/heartbeat.mjs +16 -16
  33. package/lib/images.mjs +1 -1
  34. package/lib/lifecycle.mjs +53 -53
  35. package/lib/migration.mjs +154 -154
  36. package/lib/object-format.mjs +112 -0
  37. package/lib/presentation.mjs +18 -2
  38. package/lib/process-identity.mjs +14 -14
  39. package/lib/project.mjs +39 -39
  40. package/lib/prompt-structure.mjs +7 -3
  41. package/lib/refs.mjs +26 -26
  42. package/lib/runtime.mjs +25 -25
  43. package/lib/service.mjs +126 -126
  44. package/lib/settings.mjs +50 -50
  45. package/lib/shared.mjs +67 -66
  46. package/lib/style-bundle.mjs +85 -85
  47. package/lib/style-contract.mjs +74 -35
  48. package/lib/style-evidence.mjs +39 -0
  49. package/lib/style-lifecycle.mjs +125 -120
  50. package/lib/style-report.mjs +201 -0
  51. package/lib/style-review.mjs +14 -75
  52. package/lib/task-contract.mjs +93 -59
  53. package/lib/tasks.mjs +497 -495
  54. package/lib/templates.mjs +80 -70
  55. package/lib/vision.mjs +56 -46
  56. package/lib/workspace.mjs +292 -238
  57. package/package.json +3 -5
  58. package/rules/core-guidance.json +22 -22
  59. package/skills/art-workshop/SKILL.md +17 -112
  60. package/skills/art-workshop/references/conversation.md +11 -0
  61. package/skills/art-workshop/references/expression.md +27 -0
  62. package/skills/art-workshop/references/getty.md +76 -0
  63. package/skills/art-workshop/references/project.md +109 -0
  64. package/skills/art-workshop/references/style-discussion.md +27 -0
  65. package/skills/art-workshop/scripts/getty.py +269 -0
  66. package/v-cli.plugin.json +2747 -2491
  67. package/scripts/sync-skill.mjs +0 -6
  68. /package/{skills/art-workshop → adapters/codex}/agents/openai.yaml +0 -0
package/lib/migration.mjs CHANGED
@@ -1,154 +1,154 @@
1
- import {existsSync,mkdirSync,readdirSync,cpSync,rmSync} from 'node:fs';
2
- import {join,dirname,relative,resolve} from 'node:path';
3
- import {randomUUID} from 'node:crypto';
4
- import {id,readJson,writeJson,hash,renameWithRetry} from './shared.mjs';
5
- import {createHash} from 'node:crypto';
6
- import {externalPath} from './settings.mjs';
7
- import {readFileSync} from 'node:fs';
8
- import {locked,tasks,runtimeRoot,alive,taskFile} from './runtime.mjs';
9
- import {taskStatus} from './tasks.mjs';
10
- import {assertIdle} from './lifecycle.mjs';
11
- import {ownedPath,STYLE_CATEGORIES,TASK_PURPOSES} from './workspace.mjs';
12
- import {validateImage} from './images.mjs';
13
- import {checkRun} from './executor.mjs';
14
-
15
- /** Preflight old executions and synchronous manifests without modifying evidence. */
16
- async function legacyRuns(settings,projectId){
17
- const result=new Map(),oldRoot=join(dirname(settings.file),'.runtime',hash(settings.file).slice(0,12));
18
- for(const run of tasks(oldRoot).filter(run=>(run.plan?.project??run.project)===projectId)){
19
- if(alive(run.workerPid)||!['succeeded','failed','cancelled'].includes(run.status)||run.promptId||run.unsettled||run.remoteCancellation)throw new Error('旧工程存在运行或停止未知的执行,必须先核验原运行');
20
- if(!run.finishedAt)throw new Error('旧执行缺少停止证据,不能推断完成');
21
- result.set(run.taskId,{...run,stopConfirmed:true,root:runtimeRoot(settings),migration:{source:taskFile(oldRoot,run.taskId)}});
22
- }
23
- const manifests=[];
24
- const scan=directory=>{if(!existsSync(directory))return;for(const entry of readdirSync(directory,{withFileTypes:true})){const path=ownedPath(settings.paths.output,directory,entry.name);if(entry.isDirectory())scan(path);else if(entry.name==='manifest.json')manifests.push(path);}};
25
- scan(settings.paths.output);
26
- for(const path of manifests){const manifest=readJson(path);if(manifest.schema!=='art-workshop/run'||manifest.plan?.project!==projectId)continue;
27
- if(!manifest.finishedAt)throw new Error('历史批次缺少完成证据:'+manifest.runId);
28
- const rows=checkRun(manifest,path);for(const row of rows.filter(row=>row.generated)){if(!row.integrity)throw new Error('历史候选完整性失败:'+row.file);await validateImage(readFileSync(row.path));}
29
- const runId=manifest.taskId??('task-legacy-'+hash({path,runId:manifest.runId}).slice(0,24));id(runId);
30
- const existing=result.get(runId);if(existing&&existing.plan?.planHash!==manifest.planHash)throw new Error('旧批次运行身份冲突');
31
- result.set(runId,{...(existing??{}),schema:'art-workshop/task',taskId:runId,status:manifest.summary?.failed?'failed':'succeeded',stopConfirmed:true,createdAt:manifest.startedAt,finishedAt:manifest.finishedAt,plan:manifest.plan,items:manifest.plan.items,manifestPath:path,root:runtimeRoot(settings),outputRoot:settings.paths.output,migration:{...existing?.migration,manifestRunId:manifest.runId,review:manifest.review??[]}});
32
- }
33
- return [...result.values()];
34
- }
35
-
36
- /** Explicit one-time upgrade. Readers never fall back to legacy documents. */
37
- export async function upgradeProject(root,projectId,{dry=true,referenceAssignments={},settings}={}){
38
- if(!dry&&!settings)throw new Error('升级必须提供执行配置以检查运行占用');
39
- const upgrade=async()=>{
40
- id(projectId);
41
- const journal=ownedPath(root,'.runtime/upgrades',projectId+'.json');
42
- if(existsSync(journal)){
43
- if(dry)throw new Error('升级事务未完成,请先显式执行 project upgrade 恢复原工程');
44
- const transaction=readJson(journal),source=ownedPath(root,'projects',projectId);
45
- if(transaction.schema!=='art-workshop/upgrade'||transaction.project!==projectId)throw new Error('升级事务身份不匹配');
46
- const backup=ownedPath(root,'backups',transaction.backup),staging=ownedPath(root,'projects',transaction.staging);
47
- if(existsSync(backup)){
48
- for(const run of transaction.createdRuns){const file=taskFile(runtimeRoot(settings),run.taskId);if(existsSync(file)){if(hash(readJson(file))!==run.hash)throw new Error('升级后的执行记录被修改,不能自动回滚');rmSync(file,{force:true});}}
49
- if(existsSync(source)){if(readJson(join(source,'project.json')).schemaVersion!==2)throw new Error('升级目标被修改,不能自动回滚');rmSync(source,{recursive:true,force:true});}
50
- renameWithRetry(backup,source);
51
- }
52
- if(existsSync(staging))rmSync(staging,{recursive:true,force:true});
53
- rmSync(journal,{force:true});
54
- }
55
- if(settings)assertIdle(tasks(runtimeRoot(settings)).filter(t=>t.plan?.project===projectId||t.project===projectId).map(t=>taskStatus(runtimeRoot(settings),t.taskId)),'工程');
56
- id(projectId);const source=ownedPath(root,'projects',projectId),project=readJson(ownedPath(source,'project.json'));
57
- if(project.schemaVersion===2)return {project:projectId,current:true,changes:[]};
58
- const runs=settings?await legacyRuns(settings,projectId):[];
59
- const jobs=existsSync(ownedPath(source,'jobs'))?readdirSync(ownedPath(source,'jobs')).filter(f=>f.endsWith('.json')):[];
60
- const cores=existsSync(ownedPath(source,'cores'))?readdirSync(ownedPath(source,'cores')).filter(f=>f.endsWith('.json')):[];
61
- for(const file of jobs){const config=readJson(ownedPath(source,'jobs',file));if(config.kind==='edit')for(const item of config.items??[]){if(!item.source)throw new Error('旧编辑任务缺少底图:'+file);await validateImage(readFileSync(externalPath(resolve(root,item.source),'旧编辑底图')));}}
62
- const approvedByRun=new Map(),groups=new Map(),selected=new Set();
63
- for(const run of runs){
64
- const manifest=run.manifestPath?readJson(run.manifestPath):null;
65
- const approved=manifest?checkRun(manifest,run.manifestPath).filter(row=>row.integrity&&row.generated&&(run.migration.review??[]).some(review=>review.itemId===row.itemId&&review.variantId===row.variantId&&review.file===row.file&&['content','style','asset'].every(key=>review[key]==='pass'))):[];
66
- approvedByRun.set(run.taskId,approved);
67
- for(const row of approved){const key=run.plan.job+'/'+row.itemId,entry={runId:run.taskId,row};groups.set(key,[...(groups.get(key)??[]),entry]);}
68
- }
69
- for(const [key,entries] of groups){
70
- const mapping=referenceAssignments.selections?.find(selection=>selection.task+'/'+selection.assetId===key);
71
- const choice=mapping?entries.find(entry=>entry.runId===mapping.runId&&entry.row.file===mapping.file&&entry.row.variantId===mapping.variantId):entries.length===1?entries[0]:null;
72
- if(!choice)throw new Error('同一资产存在多份旧采用记录,需在 selections 映射中明确 runId/file/variantId:'+key);
73
- selected.add(hash({runId:choice.runId,assetId:choice.row.itemId,variantId:choice.row.variantId,file:choice.row.file}));
74
- }
75
- const refs=project.refsDir;
76
- if(refs&&!referenceAssignments.confirmed)throw new Error('旧项目共享 refs 必须先明确归属映射,禁止猜测升级');
77
- const result={project:projectId,current:false,runs:runs.map(run=>({id:run.taskId,job:run.plan?.job,status:run.status})),changes:[...jobs.map(f=>'jobs/'+f+' → tasks/'+f.slice(0,-5)+'/task.json'),...cores.map(f=>'cores/'+f+' → styles/'+f.slice(0,-5)+'/core.json')],dry};
78
- if(refs){
79
- const assignments=referenceAssignments.references;if(!Array.isArray(assignments))throw new Error('参考映射必须包含 references 列表');
80
- const importRoot=externalPath(join(root,refs),'旧参考目录'),images=[];
81
- const scan=dir=>{for(const entry of readdirSync(dir,{withFileTypes:true})){const file=ownedPath(importRoot,dir,entry.name);if(entry.isDirectory())scan(file);else if(/\.(png|jpe?g|webp)$/i.test(entry.name))images.push(file);}};
82
- if(existsSync(importRoot))scan(importRoot);
83
- for(const file of images)if(!assignments.some(a=>ownedPath(importRoot,a.path)===file))throw new Error('参考未明确映射:'+file);
84
- for(const assignment of assignments){
85
- if(!['style','task'].includes(assignment.kind))throw new Error('映射对象类型非法');id(assignment.id);
86
- if(assignment.kind==='style'&&!STYLE_CATEGORIES.includes(assignment.category))throw new Error('风格映射分类非法');
87
- if(assignment.kind==='task'&&(!assignment.purposes?.length||assignment.purposes.some(p=>!TASK_PURPOSES.includes(p))))throw new Error('任务映射用途非法');
88
- const existing=ownedPath(source,assignment.kind==='style'?'styles':'tasks',assignment.id,assignment.kind+'.json');
89
- const legacy=ownedPath(source,assignment.kind==='style'?'cores':'jobs',assignment.id+'.json');
90
- if(!existsSync(existing)&&!existsSync(legacy))throw new Error('映射目标不存在:'+assignment.id);
91
- await validateImage(readFileSync(ownedPath(importRoot,assignment.path)));
92
- }
93
- }
94
- if(dry)return result;
95
- // No symlink is allowed in a managed conversion tree.
96
- const check=directory=>{for(const name of readdirSync(directory,{withFileTypes:true})){const path=ownedPath(directory,name.name);if(name.isDirectory())check(path);}};check(source);
97
- const staging=ownedPath(root,'projects',projectId+'-upgrade-'+randomUUID()),backup=ownedPath(root,'backups',projectId+'-'+randomUUID());
98
- cpSync(source,staging,{recursive:true,errorOnExist:true,force:false});
99
- try{
100
- for(const file of jobs){
101
- const objectId=file.slice(0,-5);id(objectId);const config=readJson(join(staging,'jobs',file));
102
- if(config.kind==='edit')for(const item of config.items??[]){
103
- if(!item.source)throw new Error('旧编辑任务缺少底图,不能丢弃配置:'+objectId);
104
- const input=externalPath(resolve(root,item.source),'旧编辑底图'),buffer=readFileSync(input);await validateImage(buffer);
105
- const extension=input.slice(input.lastIndexOf('.')).toLowerCase();if(!['.png','.jpg','.jpeg','.webp'].includes(extension))throw new Error('旧编辑底图格式非法');
106
- const name=randomUUID()+extension,target=ownedPath(staging,'tasks',objectId,'sources',name);mkdirSync(dirname(target),{recursive:true});cpSync(input,target,{errorOnExist:true,force:false});
107
- item.source=relative(root,ownedPath(source,'tasks',objectId,'sources',name)).replaceAll('\\','/');
108
- }
109
- writeJson(join(staging,'tasks',objectId,'task.json'),{schema:'art-workshop/task',schemaVersion:2,project:projectId,id:objectId,name:objectId,revision:1,status:'draft',createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),source:null,config,references:[],report:null});
110
- }
111
- for(const file of cores){const objectId=file.slice(0,-5);id(objectId);const core=readJson(join(staging,'cores',file));const {coreHash,...body}=core;if(hash(body)!==coreHash||core.project!==projectId||core.id!==objectId)throw new Error('旧冻结核心完整性失败');writeJson(join(staging,'styles',objectId,'core.json'),core);writeJson(join(staging,'styles',objectId,'style.json'),{schema:'art-workshop/style',schemaVersion:2,project:projectId,id:objectId,name:objectId,revision:1,status:'frozen',coreHash,createdAt:core.approvedAt,updatedAt:core.approvedAt,source:null,config:core.config,references:[],report:{data:core.report,sourceRevision:1,path:null,runId:null,sourceHash:null}});}
112
- for(const run of runs){
113
- const file=ownedPath(staging,'tasks',run.plan?.job,'task.json');if(!existsSync(file))throw new Error('历史运行没有对应任务,不能丢弃:'+run.taskId);
114
- const record=readJson(file),approved=approvedByRun.get(run.taskId);
115
- for(const row of approved){const candidateId=hash({runId:run.taskId,assetId:row.itemId,variantId:row.variantId,file:row.file}),selection={assetId:row.itemId,runId:run.taskId,candidateId,path:row.path,hash:createHash('sha256').update(readFileSync(row.path)).digest('hex'),taskConfigHash:hash(record.config),actor:'legacy-upgrade',createdAt:run.finishedAt,revision:1};
116
- if(selected.has(candidateId)){record.finalizations??=[];record.finalizations.push(selection);}else{record.finalizationHistory??=[];record.finalizationHistory.push({...selection,supersededByMigration:true});}
117
- }
118
- writeJson(file,record);
119
- const destination=taskFile(runtimeRoot(settings),run.taskId);if(existsSync(destination)&&hash(readJson(destination))!==hash(run))throw new Error('目标执行记录冲突,保留原工程');
120
- }
121
- delete project.refsDir;project.schemaVersion=2;project.revision=1;writeJson(join(staging,'project.json'),project);
122
- // Reject unresolved external refs rather than silently drop their associations.
123
- if(refs){
124
- const assignments=referenceAssignments.references;
125
- if(!Array.isArray(assignments))throw new Error('参考映射必须包含 references 列表');
126
- const importRoot=externalPath(join(root,refs),'旧参考目录');
127
- const images=[];const scan=dir=>{for(const entry of readdirSync(dir,{withFileTypes:true})){const path=ownedPath(importRoot,dir,entry.name);if(entry.isDirectory())scan(path);else if(/\.(png|jpe?g|webp)$/i.test(entry.name))images.push(path);}};if(existsSync(importRoot))scan(importRoot);
128
- for(const path of images)if(!assignments.some(a=>ownedPath(importRoot,a.path)===path))throw new Error('参考未明确映射:'+path);
129
- for(const assignment of assignments){
130
- if(!['style','task'].includes(assignment.kind))throw new Error('映射对象类型非法');id(assignment.id);
131
- if(assignment.kind==='style'&&!STYLE_CATEGORIES.includes(assignment.category))throw new Error('风格映射分类非法');
132
- if(assignment.kind==='task'&&(!assignment.purposes?.length||assignment.purposes.some(p=>!TASK_PURPOSES.includes(p))))throw new Error('任务映射用途非法');
133
- const objectDir=ownedPath(staging,assignment.kind==='style'?'styles':'tasks',assignment.id),file=ownedPath(objectDir,assignment.kind+'.json');
134
- const record=readJson(file),input=ownedPath(importRoot,assignment.path),buffer=readFileSync(input),refId='ref-'+randomUUID();
135
- const extension=input.slice(input.lastIndexOf('.')).toLowerCase();if(!['.png','.jpg','.jpeg','.webp'].includes(extension))throw new Error('参考格式非法');
136
- const target=['refs',...(assignment.kind==='style'?[assignment.category]:[]),refId+extension].join('/');
137
- const destination=ownedPath(objectDir,target);mkdirSync(join(destination,'..'),{recursive:true});
138
- cpSync(input,destination,{recursive:false,force:false});
139
- record.references.push({id:refId,path:target,hash:createHash('sha256').update(buffer).digest('hex'),source:input,category:assignment.category??null,purposes:assignment.purposes??[],usage:'understand',note:assignment.note??'',ignore:assignment.ignore??''});writeJson(file,record);
140
- }
141
- }
142
- for(const dir of ['jobs','cores'])rmSync(ownedPath(staging,dir),{recursive:true,force:true});
143
- const createdRuns=runs.filter(run=>!existsSync(taskFile(runtimeRoot(settings),run.taskId))).map(run=>({taskId:run.taskId,hash:hash(run)}));
144
- writeJson(journal,{schema:'art-workshop/upgrade',project:projectId,backup:relative(join(root,'backups'),backup),staging:relative(join(root,'projects'),staging),createdRuns});
145
- mkdirSync(join(root,'backups'),{recursive:true});renameWithRetry(source,backup);
146
- const created=[];
147
- try{renameWithRetry(staging,source);for(const run of runs){const file=taskFile(runtimeRoot(settings),run.taskId);if(!existsSync(file)){created.push(file);writeJson(file,run);}}}
148
- catch(error){for(const file of created)rmSync(file,{force:true});if(existsSync(source))rmSync(ownedPath(root,source),{recursive:true,force:true});renameWithRetry(backup,source);rmSync(journal,{force:true});throw error;}
149
- rmSync(journal,{force:true});
150
- return {...result,backup};
151
- }finally{if(existsSync(staging))rmSync(ownedPath(root,'projects',staging),{recursive:true,force:true});}
152
- };
153
- return dry?upgrade():locked(runtimeRoot(settings),'control',upgrade);
154
- }
1
+ import {existsSync,mkdirSync,readdirSync,cpSync,rmSync} from 'node:fs';
2
+ import {join,dirname,relative,resolve} from 'node:path';
3
+ import {randomUUID} from 'node:crypto';
4
+ import {id,readJson,writeJson,hash,renameWithRetry} from './shared.mjs';
5
+ import {createHash} from 'node:crypto';
6
+ import {externalPath} from './settings.mjs';
7
+ import {readFileSync} from 'node:fs';
8
+ import {locked,tasks,runtimeRoot,alive,taskFile} from './runtime.mjs';
9
+ import {taskStatus} from './tasks.mjs';
10
+ import {assertIdle} from './lifecycle.mjs';
11
+ import {ownedPath,STYLE_CATEGORIES,TASK_PURPOSES} from './workspace.mjs';
12
+ import {validateImage} from './images.mjs';
13
+ import {checkRun} from './executor.mjs';
14
+
15
+ /** Preflight old executions and synchronous manifests without modifying evidence. */
16
+ async function legacyRuns(settings,projectId){
17
+ const result=new Map(),oldRoot=join(dirname(settings.file),'.runtime',hash(settings.file).slice(0,12));
18
+ for(const run of tasks(oldRoot).filter(run=>(run.plan?.project??run.project)===projectId)){
19
+ if(alive(run.workerPid)||!['succeeded','failed','cancelled'].includes(run.status)||run.promptId||run.unsettled||run.remoteCancellation)throw new Error('旧工程存在运行或停止未知的执行,必须先核验原运行');
20
+ if(!run.finishedAt)throw new Error('旧执行缺少停止证据,不能推断完成');
21
+ result.set(run.taskId,{...run,stopConfirmed:true,root:runtimeRoot(settings),migration:{source:taskFile(oldRoot,run.taskId)}});
22
+ }
23
+ const manifests=[];
24
+ const scan=directory=>{if(!existsSync(directory))return;for(const entry of readdirSync(directory,{withFileTypes:true})){const path=ownedPath(settings.paths.output,directory,entry.name);if(entry.isDirectory())scan(path);else if(entry.name==='manifest.json')manifests.push(path);}};
25
+ scan(settings.paths.output);
26
+ for(const path of manifests){const manifest=readJson(path);if(manifest.schema!=='art-workshop/run'||manifest.plan?.project!==projectId)continue;
27
+ if(!manifest.finishedAt)throw new Error('历史批次缺少完成证据:'+manifest.runId);
28
+ const rows=checkRun(manifest,path);for(const row of rows.filter(row=>row.generated)){if(!row.integrity)throw new Error('历史候选完整性失败:'+row.file);await validateImage(readFileSync(row.path));}
29
+ const runId=manifest.taskId??('task-legacy-'+hash({path,runId:manifest.runId}).slice(0,24));id(runId);
30
+ const existing=result.get(runId);if(existing&&existing.plan?.planHash!==manifest.planHash)throw new Error('旧批次运行身份冲突');
31
+ result.set(runId,{...(existing??{}),schema:'art-workshop/task',taskId:runId,status:manifest.summary?.failed?'failed':'succeeded',stopConfirmed:true,createdAt:manifest.startedAt,finishedAt:manifest.finishedAt,plan:manifest.plan,items:manifest.plan.items,manifestPath:path,root:runtimeRoot(settings),outputRoot:settings.paths.output,migration:{...existing?.migration,manifestRunId:manifest.runId,review:manifest.review??[]}});
32
+ }
33
+ return [...result.values()];
34
+ }
35
+
36
+ /** Explicit one-time upgrade. Readers never fall back to legacy documents. */
37
+ export async function upgradeProject(root,projectId,{dry=true,referenceAssignments={},settings}={}){
38
+ if(!dry&&!settings)throw new Error('升级必须提供执行配置以检查运行占用');
39
+ const upgrade=async()=>{
40
+ id(projectId);
41
+ const journal=ownedPath(root,'.runtime/upgrades',projectId+'.json');
42
+ if(existsSync(journal)){
43
+ if(dry)throw new Error('升级事务未完成,请先显式执行 project upgrade 恢复原工程');
44
+ const transaction=readJson(journal),source=ownedPath(root,'projects',projectId);
45
+ if(transaction.schema!=='art-workshop/upgrade'||transaction.project!==projectId)throw new Error('升级事务身份不匹配');
46
+ const backup=ownedPath(root,'backups',transaction.backup),staging=ownedPath(root,'projects',transaction.staging);
47
+ if(existsSync(backup)){
48
+ for(const run of transaction.createdRuns){const file=taskFile(runtimeRoot(settings),run.taskId);if(existsSync(file)){if(hash(readJson(file))!==run.hash)throw new Error('升级后的执行记录被修改,不能自动回滚');rmSync(file,{force:true});}}
49
+ if(existsSync(source)){if(readJson(join(source,'project.json')).schemaVersion!==2)throw new Error('升级目标被修改,不能自动回滚');rmSync(source,{recursive:true,force:true});}
50
+ renameWithRetry(backup,source);
51
+ }
52
+ if(existsSync(staging))rmSync(staging,{recursive:true,force:true});
53
+ rmSync(journal,{force:true});
54
+ }
55
+ if(settings)assertIdle(tasks(runtimeRoot(settings)).filter(t=>t.plan?.project===projectId||t.project===projectId).map(t=>taskStatus(runtimeRoot(settings),t.taskId)),'工程');
56
+ id(projectId);const source=ownedPath(root,'projects',projectId),project=readJson(ownedPath(source,'project.json'));
57
+ if(project.schemaVersion===2)return {project:projectId,current:true,changes:[]};
58
+ const runs=settings?await legacyRuns(settings,projectId):[];
59
+ const jobs=existsSync(ownedPath(source,'jobs'))?readdirSync(ownedPath(source,'jobs')).filter(f=>f.endsWith('.json')):[];
60
+ const cores=existsSync(ownedPath(source,'cores'))?readdirSync(ownedPath(source,'cores')).filter(f=>f.endsWith('.json')):[];
61
+ for(const file of jobs){const config=readJson(ownedPath(source,'jobs',file));if(config.kind==='edit')for(const item of config.items??[]){if(!item.source)throw new Error('旧编辑任务缺少底图:'+file);await validateImage(readFileSync(externalPath(resolve(root,item.source),'旧编辑底图')));}}
62
+ const approvedByRun=new Map(),groups=new Map(),selected=new Set();
63
+ for(const run of runs){
64
+ const manifest=run.manifestPath?readJson(run.manifestPath):null;
65
+ const approved=manifest?checkRun(manifest,run.manifestPath).filter(row=>row.integrity&&row.generated&&(run.migration.review??[]).some(review=>review.itemId===row.itemId&&review.variantId===row.variantId&&review.file===row.file&&['content','style','asset'].every(key=>review[key]==='pass'))):[];
66
+ approvedByRun.set(run.taskId,approved);
67
+ for(const row of approved){const key=run.plan.job+'/'+row.itemId,entry={runId:run.taskId,row};groups.set(key,[...(groups.get(key)??[]),entry]);}
68
+ }
69
+ for(const [key,entries] of groups){
70
+ const mapping=referenceAssignments.selections?.find(selection=>selection.task+'/'+selection.assetId===key);
71
+ const choice=mapping?entries.find(entry=>entry.runId===mapping.runId&&entry.row.file===mapping.file&&entry.row.variantId===mapping.variantId):entries.length===1?entries[0]:null;
72
+ if(!choice)throw new Error('同一资产存在多份旧采用记录,需在 selections 映射中明确 runId/file/variantId:'+key);
73
+ selected.add(hash({runId:choice.runId,assetId:choice.row.itemId,variantId:choice.row.variantId,file:choice.row.file}));
74
+ }
75
+ const refs=project.refsDir;
76
+ if(refs&&!referenceAssignments.confirmed)throw new Error('旧项目共享 refs 必须先明确归属映射,禁止猜测升级');
77
+ const result={project:projectId,current:false,runs:runs.map(run=>({id:run.taskId,job:run.plan?.job,status:run.status})),changes:[...jobs.map(f=>'jobs/'+f+' → tasks/'+f.slice(0,-5)+'/task.json'),...cores.map(f=>'cores/'+f+' → styles/'+f.slice(0,-5)+'/core.json')],dry};
78
+ if(refs){
79
+ const assignments=referenceAssignments.references;if(!Array.isArray(assignments))throw new Error('参考映射必须包含 references 列表');
80
+ const importRoot=externalPath(join(root,refs),'旧参考目录'),images=[];
81
+ const scan=dir=>{for(const entry of readdirSync(dir,{withFileTypes:true})){const file=ownedPath(importRoot,dir,entry.name);if(entry.isDirectory())scan(file);else if(/\.(png|jpe?g|webp)$/i.test(entry.name))images.push(file);}};
82
+ if(existsSync(importRoot))scan(importRoot);
83
+ for(const file of images)if(!assignments.some(a=>ownedPath(importRoot,a.path)===file))throw new Error('参考未明确映射:'+file);
84
+ for(const assignment of assignments){
85
+ if(!['style','task'].includes(assignment.kind))throw new Error('映射对象类型非法');id(assignment.id);
86
+ if(assignment.kind==='style'&&!STYLE_CATEGORIES.includes(assignment.category))throw new Error('风格映射分类非法');
87
+ if(assignment.kind==='task'&&(!assignment.purposes?.length||assignment.purposes.some(p=>!TASK_PURPOSES.includes(p))))throw new Error('任务映射用途非法');
88
+ const existing=ownedPath(source,assignment.kind==='style'?'styles':'tasks',assignment.id,assignment.kind+'.json');
89
+ const legacy=ownedPath(source,assignment.kind==='style'?'cores':'jobs',assignment.id+'.json');
90
+ if(!existsSync(existing)&&!existsSync(legacy))throw new Error('映射目标不存在:'+assignment.id);
91
+ await validateImage(readFileSync(ownedPath(importRoot,assignment.path)));
92
+ }
93
+ }
94
+ if(dry)return result;
95
+ // No symlink is allowed in a managed conversion tree.
96
+ const check=directory=>{for(const name of readdirSync(directory,{withFileTypes:true})){const path=ownedPath(directory,name.name);if(name.isDirectory())check(path);}};check(source);
97
+ const staging=ownedPath(root,'projects',projectId+'-upgrade-'+randomUUID()),backup=ownedPath(root,'backups',projectId+'-'+randomUUID());
98
+ cpSync(source,staging,{recursive:true,errorOnExist:true,force:false});
99
+ try{
100
+ for(const file of jobs){
101
+ const objectId=file.slice(0,-5);id(objectId);const config=readJson(join(staging,'jobs',file));
102
+ if(config.kind==='edit')for(const item of config.items??[]){
103
+ if(!item.source)throw new Error('旧编辑任务缺少底图,不能丢弃配置:'+objectId);
104
+ const input=externalPath(resolve(root,item.source),'旧编辑底图'),buffer=readFileSync(input);await validateImage(buffer);
105
+ const extension=input.slice(input.lastIndexOf('.')).toLowerCase();if(!['.png','.jpg','.jpeg','.webp'].includes(extension))throw new Error('旧编辑底图格式非法');
106
+ const name=randomUUID()+extension,target=ownedPath(staging,'tasks',objectId,'sources',name);mkdirSync(dirname(target),{recursive:true});cpSync(input,target,{errorOnExist:true,force:false});
107
+ item.source=relative(root,ownedPath(source,'tasks',objectId,'sources',name)).replaceAll('\\','/');
108
+ }
109
+ writeJson(join(staging,'tasks',objectId,'task.json'),{schema:'art-workshop/task',schemaVersion:2,project:projectId,id:objectId,name:objectId,revision:1,status:'draft',createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),source:null,config,references:[],report:null});
110
+ }
111
+ for(const file of cores){const objectId=file.slice(0,-5);id(objectId);const core=readJson(join(staging,'cores',file));const {coreHash,...body}=core;if(hash(body)!==coreHash||core.project!==projectId||core.id!==objectId)throw new Error('旧冻结核心完整性失败');writeJson(join(staging,'styles',objectId,'core.json'),core);writeJson(join(staging,'styles',objectId,'style.json'),{schema:'art-workshop/style',schemaVersion:2,project:projectId,id:objectId,name:objectId,revision:1,status:'frozen',coreHash,createdAt:core.approvedAt,updatedAt:core.approvedAt,source:null,config:core.config,references:[],report:{data:core.report,sourceRevision:1,path:null,runId:null,sourceHash:null}});}
112
+ for(const run of runs){
113
+ const file=ownedPath(staging,'tasks',run.plan?.job,'task.json');if(!existsSync(file))throw new Error('历史运行没有对应任务,不能丢弃:'+run.taskId);
114
+ const record=readJson(file),approved=approvedByRun.get(run.taskId);
115
+ for(const row of approved){const candidateId=hash({runId:run.taskId,assetId:row.itemId,variantId:row.variantId,file:row.file}),selection={assetId:row.itemId,runId:run.taskId,candidateId,path:row.path,hash:createHash('sha256').update(readFileSync(row.path)).digest('hex'),taskConfigHash:hash(record.config),actor:'legacy-upgrade',createdAt:run.finishedAt,revision:1};
116
+ if(selected.has(candidateId)){record.finalizations??=[];record.finalizations.push(selection);}else{record.finalizationHistory??=[];record.finalizationHistory.push({...selection,supersededByMigration:true});}
117
+ }
118
+ writeJson(file,record);
119
+ const destination=taskFile(runtimeRoot(settings),run.taskId);if(existsSync(destination)&&hash(readJson(destination))!==hash(run))throw new Error('目标执行记录冲突,保留原工程');
120
+ }
121
+ delete project.refsDir;project.schemaVersion=2;project.revision=1;writeJson(join(staging,'project.json'),project);
122
+ // Reject unresolved external refs rather than silently drop their associations.
123
+ if(refs){
124
+ const assignments=referenceAssignments.references;
125
+ if(!Array.isArray(assignments))throw new Error('参考映射必须包含 references 列表');
126
+ const importRoot=externalPath(join(root,refs),'旧参考目录');
127
+ const images=[];const scan=dir=>{for(const entry of readdirSync(dir,{withFileTypes:true})){const path=ownedPath(importRoot,dir,entry.name);if(entry.isDirectory())scan(path);else if(/\.(png|jpe?g|webp)$/i.test(entry.name))images.push(path);}};if(existsSync(importRoot))scan(importRoot);
128
+ for(const path of images)if(!assignments.some(a=>ownedPath(importRoot,a.path)===path))throw new Error('参考未明确映射:'+path);
129
+ for(const assignment of assignments){
130
+ if(!['style','task'].includes(assignment.kind))throw new Error('映射对象类型非法');id(assignment.id);
131
+ if(assignment.kind==='style'&&!STYLE_CATEGORIES.includes(assignment.category))throw new Error('风格映射分类非法');
132
+ if(assignment.kind==='task'&&(!assignment.purposes?.length||assignment.purposes.some(p=>!TASK_PURPOSES.includes(p))))throw new Error('任务映射用途非法');
133
+ const objectDir=ownedPath(staging,assignment.kind==='style'?'styles':'tasks',assignment.id),file=ownedPath(objectDir,assignment.kind+'.json');
134
+ const record=readJson(file),input=ownedPath(importRoot,assignment.path),buffer=readFileSync(input),refId='ref-'+randomUUID();
135
+ const extension=input.slice(input.lastIndexOf('.')).toLowerCase();if(!['.png','.jpg','.jpeg','.webp'].includes(extension))throw new Error('参考格式非法');
136
+ const target=['refs',...(assignment.kind==='style'?[assignment.category]:[]),refId+extension].join('/');
137
+ const destination=ownedPath(objectDir,target);mkdirSync(join(destination,'..'),{recursive:true});
138
+ cpSync(input,destination,{recursive:false,force:false});
139
+ record.references.push({id:refId,path:target,hash:createHash('sha256').update(buffer).digest('hex'),source:input,category:assignment.category??null,purposes:assignment.purposes??[],usage:'understand',note:assignment.note??'',ignore:assignment.ignore??''});writeJson(file,record);
140
+ }
141
+ }
142
+ for(const dir of ['jobs','cores'])rmSync(ownedPath(staging,dir),{recursive:true,force:true});
143
+ const createdRuns=runs.filter(run=>!existsSync(taskFile(runtimeRoot(settings),run.taskId))).map(run=>({taskId:run.taskId,hash:hash(run)}));
144
+ writeJson(journal,{schema:'art-workshop/upgrade',project:projectId,backup:relative(join(root,'backups'),backup),staging:relative(join(root,'projects'),staging),createdRuns});
145
+ mkdirSync(join(root,'backups'),{recursive:true});renameWithRetry(source,backup);
146
+ const created=[];
147
+ try{renameWithRetry(staging,source);for(const run of runs){const file=taskFile(runtimeRoot(settings),run.taskId);if(!existsSync(file)){created.push(file);writeJson(file,run);}}}
148
+ catch(error){for(const file of created)rmSync(file,{force:true});if(existsSync(source))rmSync(ownedPath(root,source),{recursive:true,force:true});renameWithRetry(backup,source);rmSync(journal,{force:true});throw error;}
149
+ rmSync(journal,{force:true});
150
+ return {...result,backup};
151
+ }finally{if(existsSync(staging))rmSync(ownedPath(root,'projects',staging),{recursive:true,force:true});}
152
+ };
153
+ return dry?upgrade():locked(runtimeRoot(settings),'control',upgrade);
154
+ }
@@ -0,0 +1,112 @@
1
+ import { keys } from "./shared.mjs";
2
+ import { STYLE_SCHEMA_VERSION, STYLE_CATEGORIES } from "./style-contract.mjs";
3
+ import {
4
+ GENERATION_FIELDS,
5
+ EDIT_FIELDS,
6
+ TASK_FIELDS,
7
+ } from "./task-contract.mjs";
8
+
9
+ /** Format recognition only. Missing content and absent optional fields are not deprecation. */
10
+ export function inspectObjectFormat(record, { core, dependency } = {}) {
11
+ const reasons = [];
12
+ if (
13
+ record.readError ||
14
+ (record.source?.kind === "migration" && !record.migration)
15
+ )
16
+ return {
17
+ status: "unreadable",
18
+ reasons: [record.readError ?? "迁移来源准备尚未完成,请从原对象重试派生"],
19
+ canEdit: false,
20
+ canDerive: false,
21
+ };
22
+ const kind = record.schema?.slice("art-workshop/".length);
23
+ if (
24
+ !record.config ||
25
+ typeof record.config !== "object" ||
26
+ Array.isArray(record.config)
27
+ )
28
+ return {
29
+ status: "unreadable",
30
+ reasons: ["配置数据无法读取"],
31
+ canEdit: false,
32
+ canDerive: false,
33
+ };
34
+ if (record.schemaVersion !== 2) reasons.push("对象格式已弃用");
35
+ try {
36
+ const c = record.config;
37
+ if (kind === "style") {
38
+ // Original frozen configs may use an earlier structured drawing contract.
39
+ keys(
40
+ c,
41
+ ["description", "constraints", "rules", "analysis"],
42
+ "style config",
43
+ );
44
+ if (c.rules !== undefined) {
45
+ if (!Array.isArray(c.rules)) throw Error("风格规则结构已弃用");
46
+ for (const rule of c.rules)
47
+ keys(
48
+ rule,
49
+ ["id", "scope", "strength", "instruction", "when", "negative"],
50
+ "style rule",
51
+ );
52
+ }
53
+ if (
54
+ record.report &&
55
+ record.report.data?.schemaVersion !== STYLE_SCHEMA_VERSION
56
+ )
57
+ reasons.push("风格报告职责格式已弃用");
58
+ if (
59
+ (record.references ?? []).some(
60
+ (r) => !STYLE_CATEGORIES.includes(r.category),
61
+ )
62
+ )
63
+ reasons.push("风格参考分类已弃用");
64
+ if (
65
+ record.status === "frozen" &&
66
+ (!core || core.schemaVersion !== STYLE_SCHEMA_VERSION)
67
+ )
68
+ reasons.push("冻结风格职责格式已弃用");
69
+ } else if (kind === "task") {
70
+ keys(c, TASK_FIELDS[c.kind] ?? [], "task config");
71
+ if (!["generate", "edit"].includes(c.kind))
72
+ reasons.push("任务类型格式已弃用");
73
+ for (const item of c.items ?? []) {
74
+ keys(
75
+ item,
76
+ c.kind === "edit" ? EDIT_FIELDS : GENERATION_FIELDS.item,
77
+ "item",
78
+ );
79
+ if (c.kind === "generate")
80
+ for (const [field, shape] of [
81
+ ["entities", "entity"],
82
+ ["effects", "effect"],
83
+ ["relations", "relation"],
84
+ ["variants", "variant"],
85
+ ])
86
+ for (const row of item[field] ?? [])
87
+ keys(row, GENERATION_FIELDS[shape], shape);
88
+ }
89
+ if (c.core && (!dependency || dependency.status !== "current"))
90
+ reasons.push("所用风格已弃用或不可用");
91
+ } else reasons.push("对象类型格式已弃用");
92
+ } catch (error) {
93
+ reasons.push(error.message);
94
+ }
95
+ const status = reasons.length ? "deprecated" : "current";
96
+ if (reasons.length) reasons[reasons.length - 1] += ",请派生迁移";
97
+ return {
98
+ status,
99
+ reasons,
100
+ canEdit: status === "current" && record.status !== "frozen",
101
+ canDerive: !["discarded", "cleanup-required"].includes(record.status),
102
+ };
103
+ }
104
+ export function assertSupportedObject(format) {
105
+ if (format.status !== "current")
106
+ throw Object.assign(
107
+ new Error(
108
+ "格式弃用:" + format.reasons.join(";") + "。请派生迁移为当前格式草稿",
109
+ ),
110
+ { code: "FORMAT_DEPRECATED" },
111
+ );
112
+ }
@@ -1,5 +1,16 @@
1
1
  import {description} from './shared.mjs';
2
2
  import { keys, choice, text, hex } from './shared.mjs';
3
+ export function validateLightProfile(profile){
4
+ const fields=['lightDirection','lightQuality'];
5
+ const declared=fields.some(k=>profile.allowedOverrides?.[k]!==undefined||profile.defaults?.[k]!==undefined);
6
+ if(!declared)return false;
7
+ for(const k of fields){
8
+ const allowed=profile.allowedOverrides?.[k];
9
+ if(!Array.isArray(allowed)||!allowed.length||allowed.some(v=>typeof v!=='string'||!v.trim()))throw new Error('光照方向与质感必须成对声明非空词表:'+k);
10
+ choice(profile.defaults?.[k],allowed,'defaults.'+k);
11
+ }
12
+ return true;
13
+ }
3
14
  export function background(value,allowScene=false) {
4
15
  keys(value,['type','color','from','to','description'],'background');
5
16
  if(value.type==='transparent') { keys(value,['type'],'transparent background'); return '最终交付透明 PNG。中间图使用均匀纯洋红 #FF00FF 背景供自动去背景;主体不得含洋红背景色、背景投影、渐变或棋盘格;保留完整主体和边缘。'; }
@@ -9,13 +20,18 @@ export function background(value,allowScene=false) {
9
20
  throw new Error('背景类型不支持或资产不允许场景');
10
21
  }
11
22
  export function presentation(profile,overrides={},design=null) {
12
- keys(overrides,['preset','view','direction','occupancy','effectIntensity','background','focalTarget'],'composition');
23
+ keys(overrides,['preset','view','direction','occupancy','effectIntensity','background','focalTarget','lightDirection','lightQuality'],'composition');
24
+ const light=validateLightProfile(profile);
25
+ for(const k of ['lightDirection','lightQuality']){
26
+ if(!light&&Object.hasOwn(overrides,k))throw new Error('当前资产规格未开放光照词汇:'+k);
27
+ }
13
28
  const c={...profile.defaults,...overrides};
29
+ if(light)for(const k of ['lightDirection','lightQuality'])choice(c[k],profile.allowedOverrides[k],k);
14
30
  for(const k of ['preset','view','direction','effectIntensity']) choice(c[k],profile.allowedOverrides[k],k);
15
31
  const range=profile.allowedOverrides.occupancy;
16
32
  if(!Number.isFinite(c.occupancy)||c.occupancy<range.min||c.occupancy>range.max) throw new Error('主体占比越界');
17
33
  const bg=background(c.background,profile.constraints.scene);
18
- return {value:c,prompt:`${profile.presets[c.preset]}。视角:${c.view};方向:${c.direction};${design?'保持设计宽高比与四周安全留白':'整体占画幅约 '+c.occupancy*100+'%'};效果强度:${c.effectIntensity}。\n${bg}`,background:bg};
34
+ return {value:c,prompt:`${profile.presets[c.preset]}。视角:${c.view};方向:${c.direction};${design?'保持设计宽高比与四周安全留白':'整体占画幅约 '+c.occupancy*100+'%'};效果强度:${c.effectIntensity}${light?';光照:'+c.lightDirection+','+c.lightQuality:''}。\n${bg}`,background:bg};
19
35
  }
20
36
  export function assetPrompt(profile) {
21
37
  const c=profile.constraints;
@@ -1,14 +1,14 @@
1
- import {execFileSync} from 'node:child_process';
2
- export function processIdentity(pid) {
3
- if(!Number.isSafeInteger(pid)||pid<1)return null;
4
- try {
5
- if(process.platform==='win32') {
6
- const script=`$p=Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}"; if($p){[pscustomobject]@{pid=$p.ProcessId;exe=$p.ExecutablePath;created=$p.CreationDate.ToUniversalTime().ToString('o');command=$p.CommandLine}|ConvertTo-Json -Compress}`;
7
- const output=execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{encoding:'utf8',windowsHide:true}).trim();
8
- return output?JSON.parse(output):null;
9
- }
10
- const created=execFileSync('ps',['-p',String(pid),'-o','lstart='],{encoding:'utf8'}).trim();
11
- const command=execFileSync('ps',['-p',String(pid),'-o','args='],{encoding:'utf8'}).trim();
12
- return created?{pid,created,command}:null;
13
- }catch{return null;}
14
- }
1
+ import {execFileSync} from 'node:child_process';
2
+ export function processIdentity(pid) {
3
+ if(!Number.isSafeInteger(pid)||pid<1)return null;
4
+ try {
5
+ if(process.platform==='win32') {
6
+ const script=`$p=Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}"; if($p){[pscustomobject]@{pid=$p.ProcessId;exe=$p.ExecutablePath;created=$p.CreationDate.ToUniversalTime().ToString('o');command=$p.CommandLine}|ConvertTo-Json -Compress}`;
7
+ const output=execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{encoding:'utf8',windowsHide:true}).trim();
8
+ return output?JSON.parse(output):null;
9
+ }
10
+ const created=execFileSync('ps',['-p',String(pid),'-o','lstart='],{encoding:'utf8'}).trim();
11
+ const command=execFileSync('ps',['-p',String(pid),'-o','args='],{encoding:'utf8'}).trim();
12
+ return created?{pid,created,command}:null;
13
+ }catch{return null;}
14
+ }
package/lib/project.mjs CHANGED
@@ -1,39 +1,39 @@
1
- import { join, resolve } from 'node:path';
2
- import { loadSettings,externalPath } from './settings.mjs';
3
- import { readJson, id, keys, text } from './shared.mjs';
4
- import {ownedPath,readObject} from './workspace.mjs';
5
- import {existsSync} from 'node:fs';
6
-
7
- export const ROOT = loadSettings().paths.workspace;
8
- export function projectPath(root, projectId, folder, name) {
9
- id(projectId, 'project'); id(name, folder);
10
- return folder==='cores'?ownedPath(root,'projects',projectId,'styles',name,'core.json'):ownedPath(root,'projects',projectId,folder,name+'.json');
11
- }
12
- export function loadProject(projectId, root = ROOT) {
13
- id(projectId, 'project');
14
- if(existsSync(ownedPath(root,'.runtime/upgrades',projectId+'.json')))throw new Error('工程升级事务未完成,请显式 project upgrade 恢复');
15
- const project = readJson(externalPath(join(root, 'projects', projectId, 'project.json')));
16
- return validateProject(project,projectId);
17
- }
18
- export function validateProject(project,projectId){
19
- id(projectId,'project');
20
- keys(project, ['schemaVersion','revision','id', 'name', 'analysisModel', 'execution', 'cores', 'defaultCore'], 'project');
21
- if(project.schemaVersion!==2)throw new Error('工程格式需显式升级,不能读取旧结构');
22
- if (project.id !== projectId) throw new Error('工程身份不匹配');
23
- text(project.name, 'project.name'); text(project.analysisModel, 'analysisModel');
24
- if (!Array.isArray(project.cores)) throw new Error('project.cores 必须为数组');
25
- project.cores.forEach(x => id(x, 'core'));
26
- if (new Set(project.cores).size !== project.cores.length) throw new Error('工程核心列表重复');
27
- if (project.defaultCore !== null && !project.cores.includes(project.defaultCore)) throw new Error('defaultCore 不属于该工程');
28
- return project;
29
- }
30
- export function loadJob(projectId, jobId, module, root = ROOT) {
31
- const record=readObject(root,projectId,'task',jobId),job=record.config;
32
- if(record.status==='discarded'||job.project!==projectId||job.kind!==module)throw new Error('任务工程或模块不匹配');
33
- return job;
34
- }
35
-
36
- export function sourcePath(root, path) {
37
- text(path, 'source.path', 1024);
38
- return externalPath(resolve(root, path),'资源');
39
- }
1
+ import { join, resolve } from 'node:path';
2
+ import { loadSettings,externalPath } from './settings.mjs';
3
+ import { readJson, id, keys, text } from './shared.mjs';
4
+ import {ownedPath,readObject} from './workspace.mjs';
5
+ import {existsSync} from 'node:fs';
6
+
7
+ export const ROOT = loadSettings().paths.workspace;
8
+ export function projectPath(root, projectId, folder, name) {
9
+ id(projectId, 'project'); id(name, folder);
10
+ return folder==='cores'?ownedPath(root,'projects',projectId,'styles',name,'core.json'):ownedPath(root,'projects',projectId,folder,name+'.json');
11
+ }
12
+ export function loadProject(projectId, root = ROOT) {
13
+ id(projectId, 'project');
14
+ if(existsSync(ownedPath(root,'.runtime/upgrades',projectId+'.json')))throw new Error('工程升级事务未完成,请显式 project upgrade 恢复');
15
+ const project = readJson(externalPath(join(root, 'projects', projectId, 'project.json')));
16
+ return validateProject(project,projectId);
17
+ }
18
+ export function validateProject(project,projectId){
19
+ id(projectId,'project');
20
+ keys(project, ['schemaVersion','revision','id', 'name', 'analysisModel', 'execution', 'cores', 'defaultCore'], 'project');
21
+ if(project.schemaVersion!==2)throw new Error('工程格式需显式升级,不能读取旧结构');
22
+ if (project.id !== projectId) throw new Error('工程身份不匹配');
23
+ text(project.name, 'project.name'); text(project.analysisModel, 'analysisModel');
24
+ if (!Array.isArray(project.cores)) throw new Error('project.cores 必须为数组');
25
+ project.cores.forEach(x => id(x, 'core'));
26
+ if (new Set(project.cores).size !== project.cores.length) throw new Error('工程核心列表重复');
27
+ if (project.defaultCore !== null && !project.cores.includes(project.defaultCore)) throw new Error('defaultCore 不属于该工程');
28
+ return project;
29
+ }
30
+ export function loadJob(projectId, jobId, module, root = ROOT) {
31
+ const record=readObject(root,projectId,'task',jobId),job=record.config;
32
+ if(record.status==='discarded'||job.project!==projectId||job.kind!==module)throw new Error('任务工程或模块不匹配');
33
+ return job;
34
+ }
35
+
36
+ export function sourcePath(root, path) {
37
+ text(path, 'source.path', 1024);
38
+ return externalPath(resolve(root, path),'资源');
39
+ }