@kevlns/art-workshop 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/AGENTS.md +25 -25
  2. package/LICENSE +21 -21
  3. package/README.md +63 -63
  4. package/art-workshop.mjs +174 -174
  5. package/docs/configuration.md +82 -82
  6. package/docs/core-guidance.md +50 -50
  7. package/docs/data-formats.md +85 -85
  8. package/docs/deployment.md +32 -32
  9. package/docs/local-models/qwen-image-2.1.json +73 -73
  10. package/docs/local-models/qwen-image-2.1.md +33 -33
  11. package/docs/model-architecture.md +78 -78
  12. package/docs/modes.md +67 -67
  13. package/lib/agent.mjs +32 -32
  14. package/lib/analysis-worker.mjs +32 -32
  15. package/lib/analyze.mjs +85 -85
  16. package/lib/asset-profile.mjs +23 -23
  17. package/lib/candidates.mjs +103 -103
  18. package/lib/comfy-recovery.mjs +17 -17
  19. package/lib/conversation.mjs +77 -77
  20. package/lib/core.mjs +75 -75
  21. package/lib/deployment-guide.mjs +12 -12
  22. package/lib/design.mjs +29 -29
  23. package/lib/dimensions.mjs +22 -22
  24. package/lib/edit.mjs +41 -41
  25. package/lib/environment-operations.mjs +49 -49
  26. package/lib/environment-runtime.mjs +99 -99
  27. package/lib/environments.mjs +55 -55
  28. package/lib/executor.mjs +107 -107
  29. package/lib/generate.mjs +58 -58
  30. package/lib/heartbeat.mjs +16 -16
  31. package/lib/images.mjs +1 -1
  32. package/lib/lifecycle.mjs +53 -53
  33. package/lib/migration.mjs +154 -154
  34. package/lib/process-identity.mjs +22 -14
  35. package/lib/project.mjs +39 -39
  36. package/lib/refs.mjs +26 -26
  37. package/lib/runtime.mjs +25 -25
  38. package/lib/service.mjs +134 -126
  39. package/lib/settings.mjs +50 -50
  40. package/lib/shared.mjs +67 -67
  41. package/lib/style-bundle.mjs +85 -85
  42. package/lib/style-contract.mjs +74 -74
  43. package/lib/style-lifecycle.mjs +125 -125
  44. package/lib/style-review.mjs +14 -14
  45. package/lib/task-contract.mjs +93 -93
  46. package/lib/tasks.mjs +497 -497
  47. package/lib/templates.mjs +80 -80
  48. package/lib/vision.mjs +56 -56
  49. package/lib/worker-process.mjs +6 -6
  50. package/lib/workspace.mjs +292 -292
  51. package/package.json +1 -1
  52. package/rules/core-guidance.json +22 -22
  53. package/skills/art-workshop/SKILL.md +17 -17
  54. package/skills/art-workshop/references/conversation.md +11 -11
  55. package/skills/art-workshop/references/expression.md +27 -27
  56. package/skills/art-workshop/references/project.md +109 -109
  57. package/v-cli.plugin.json +2747 -2747
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
+ }
@@ -1,14 +1,22 @@
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 inspectProcess(pid, run = execFileSync, timeout = 5000) {
3
+ if(!Number.isSafeInteger(pid)||pid<1)return {state:'missing'};
4
+ try {
5
+ const options={encoding:'utf8',windowsHide:true,timeout,stdio:['ignore','pipe','pipe']};
6
+ if(process.platform==='win32') {
7
+ const script=`$ErrorActionPreference='Stop'; $p=Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}"; if(!$p){'{"state":"missing"}'}elseif(!$p.CreationDate -or !$p.ExecutablePath -or !$p.CommandLine){'{"state":"unknown"}'}else{[pscustomobject]@{state='running';identity=[pscustomobject]@{pid=$p.ProcessId;exe=$p.ExecutablePath;created=$p.CreationDate.ToUniversalTime().ToString('o');command=$p.CommandLine}}|ConvertTo-Json -Compress}`;
8
+ const value=JSON.parse(run('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],options).trim());
9
+ if(value.state==='missing')return value;
10
+ if(value.state==='running' && value.identity?.pid===pid && value.identity.created && value.identity.command && value.identity.exe)return value;
11
+ return {state:'unknown'};
12
+ }
13
+ const created=run('ps',['-p',String(pid),'-o','lstart='],options).trim();
14
+ const command=run('ps',['-p',String(pid),'-o','args='],options).trim();
15
+ return created&&command?{state:'running',identity:{pid,created,command}}:{state:'missing'};
16
+ }catch(error){
17
+ if(process.platform!=='win32' && error.status===1 && !String(error.stdout??'').trim() && !String(error.stderr??'').trim())return {state:'missing'};
18
+ return {state:'unknown'};
19
+ }
20
+ }
21
+ // 启动时系统查询可能冷启动;登记身份仍有总上限,退出探测保持短等待。
22
+ export function processIdentity(pid) { return inspectProcess(pid, execFileSync, 15000).identity ?? null; }
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
+ }
package/lib/refs.mjs CHANGED
@@ -1,26 +1,26 @@
1
- import {existsSync,mkdirSync,statSync} from 'node:fs';
2
- import {join,resolve} from 'node:path';
3
- import {externalPath} from './settings.mjs';
4
-
5
- import {REFERENCE_CATEGORIES} from './style-contract.mjs';
6
- export {REFERENCE_CATEGORIES} from './style-contract.mjs';
7
- export function referenceRoot({defaultRefsDir,refsDir}={}) {
8
- return externalPath(refsDir??defaultRefsDir,'素材导入目录');
9
- }
10
-
11
- export function ensureReferenceDirectories(root) {
12
- root=externalPath(root,'参考目录');
13
- const paths=[root,...REFERENCE_CATEGORIES.map(category=>externalPath(join(root,category.directory),'参考分类目录'))];
14
- for(const path of paths) if(existsSync(path)&&!statSync(path).isDirectory()) throw new Error(`参考目录位置被文件占用:${path}`);
15
- for(const path of paths) mkdirSync(path,{recursive:true});
16
- return root;
17
- }
18
-
19
- export function referenceGuide(root) {
20
- return ['# 美术工坊参考职责',`素材导入目录:${root}`,'',
21
- '| 风格目录 | 提炼范围 | 示例 |','| --- | --- | --- |',
22
- ...REFERENCE_CATEGORIES.map(x=>`| ${x.directory}/ | ${x.purpose} | ${x.recommended} |`),'',
23
- '风格静态参考归属 styleId,仅在分析中理解;生成读取冻结核心,不自动上传静态参考。',
24
- '任务动态参考归属 taskId:subject/composition/pose/identity-color/surface/scene-light/text;编辑底图单独保存在 sources。',
25
- 'reference import 显式导入到对象私有目录。发现、配置与预演不创建参考目录,不自动识别、扫描或绑定素材。'].join('\n');
26
- }
1
+ import {existsSync,mkdirSync,statSync} from 'node:fs';
2
+ import {join,resolve} from 'node:path';
3
+ import {externalPath} from './settings.mjs';
4
+
5
+ import {REFERENCE_CATEGORIES} from './style-contract.mjs';
6
+ export {REFERENCE_CATEGORIES} from './style-contract.mjs';
7
+ export function referenceRoot({defaultRefsDir,refsDir}={}) {
8
+ return externalPath(refsDir??defaultRefsDir,'素材导入目录');
9
+ }
10
+
11
+ export function ensureReferenceDirectories(root) {
12
+ root=externalPath(root,'参考目录');
13
+ const paths=[root,...REFERENCE_CATEGORIES.map(category=>externalPath(join(root,category.directory),'参考分类目录'))];
14
+ for(const path of paths) if(existsSync(path)&&!statSync(path).isDirectory()) throw new Error(`参考目录位置被文件占用:${path}`);
15
+ for(const path of paths) mkdirSync(path,{recursive:true});
16
+ return root;
17
+ }
18
+
19
+ export function referenceGuide(root) {
20
+ return ['# 美术工坊参考职责',`素材导入目录:${root}`,'',
21
+ '| 风格目录 | 提炼范围 | 示例 |','| --- | --- | --- |',
22
+ ...REFERENCE_CATEGORIES.map(x=>`| ${x.directory}/ | ${x.purpose} | ${x.recommended} |`),'',
23
+ '风格静态参考归属 styleId,仅在分析中理解;生成读取冻结核心,不自动上传静态参考。',
24
+ '任务动态参考归属 taskId:subject/composition/pose/identity-color/surface/scene-light/text;编辑底图单独保存在 sources。',
25
+ 'reference import 显式导入到对象私有目录。发现、配置与预演不创建参考目录,不自动识别、扫描或绑定素材。'].join('\n');
26
+ }
package/lib/runtime.mjs CHANGED
@@ -1,25 +1,25 @@
1
- import {existsSync,mkdirSync,rmSync,readdirSync,lstatSync} from 'node:fs';
2
- import {join,resolve,relative,isAbsolute} from 'node:path';
3
- import {randomUUID} from 'node:crypto';
4
- import {readJson,writeJson,id} from './shared.mjs';
5
- export const sleep=ms=>new Promise(r=>setTimeout(r,ms));
6
- export {terminal} from './lifecycle.mjs';
7
- // A workspace owns its runs and mutation guard. Selecting another configuration
8
- // must not create a second execution registry for the same objects.
9
- export const runtimeRoot=settings=>join(resolve(settings.paths.workspace),'.runtime');
10
- export function alive(pid){try{process.kill(pid,0);return true;}catch{return false;}}
11
- export function stateRead(path){return existsSync(path)?readJson(path):null;}
12
- export async function locked(root,name,fn,{timeout=150000}={}) {
13
- if(!/^[a-z0-9-]+$/.test(name))throw new Error('非法锁名称');
14
- mkdirSync(root,{recursive:true});const path=join(root,name+'.lock'),token=randomUUID(),deadline=Date.now()+timeout;
15
- const rel=relative(resolve(root),resolve(path));if(isAbsolute(rel)||rel.startsWith('..'))throw new Error('锁路径越界');
16
- while(true){try{mkdirSync(path);writeJson(join(path,'owner.json'),{pid:process.pid,token});break;}catch(e){if(e.code!=='EEXIST')throw e;if(lstatSync(path).isSymbolicLink())throw new Error('锁目录不能是链接');const owner=stateRead(join(path,'owner.json'));if(owner&&!alive(owner.pid)){rmSync(path,{recursive:true});continue;}if(Date.now()>deadline)throw new Error('等待锁超时 '+name);await sleep(100);}}
17
- try{return await fn();}finally{if(stateRead(join(path,'owner.json'))?.token===token)rmSync(path,{recursive:true});}
18
- }
19
- export function taskFile(root,taskId){id(taskId,'task');return join(root,'tasks',taskId+'.json');}
20
- export function tasks(root){const dir=join(root,'tasks');return existsSync(dir)?readdirSync(dir).filter(x=>x.endsWith('.json')).map(x=>stateRead(join(dir,x))).filter(x=>x?.schema==='art-workshop/task'):[];}
21
- export async function http(endpoint,path,{method='GET',body,timeout=10000}={}) {
22
- const response=await fetch(new URL(path,endpoint),{method,signal:AbortSignal.timeout(timeout),...(body?{headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});
23
- if(!response.ok){const content=await response.text(),error=new Error(`ComfyUI HTTP ${response.status}: ${content.slice(0,1000)}`);error.httpStatus=response.status;try{error.response=JSON.parse(content);}catch{};throw error;}
24
- const content=await response.text();return content?JSON.parse(content):{};
25
- }
1
+ import {existsSync,mkdirSync,rmSync,readdirSync,lstatSync} from 'node:fs';
2
+ import {join,resolve,relative,isAbsolute} from 'node:path';
3
+ import {randomUUID} from 'node:crypto';
4
+ import {readJson,writeJson,id} from './shared.mjs';
5
+ export const sleep=ms=>new Promise(r=>setTimeout(r,ms));
6
+ export {terminal} from './lifecycle.mjs';
7
+ // A workspace owns its runs and mutation guard. Selecting another configuration
8
+ // must not create a second execution registry for the same objects.
9
+ export const runtimeRoot=settings=>join(resolve(settings.paths.workspace),'.runtime');
10
+ export function alive(pid){try{process.kill(pid,0);return true;}catch{return false;}}
11
+ export function stateRead(path){return existsSync(path)?readJson(path):null;}
12
+ export async function locked(root,name,fn,{timeout=150000}={}) {
13
+ if(!/^[a-z0-9-]+$/.test(name))throw new Error('非法锁名称');
14
+ mkdirSync(root,{recursive:true});const path=join(root,name+'.lock'),token=randomUUID(),deadline=Date.now()+timeout;
15
+ const rel=relative(resolve(root),resolve(path));if(isAbsolute(rel)||rel.startsWith('..'))throw new Error('锁路径越界');
16
+ while(true){try{mkdirSync(path);writeJson(join(path,'owner.json'),{pid:process.pid,token});break;}catch(e){if(e.code!=='EEXIST')throw e;if(lstatSync(path).isSymbolicLink())throw new Error('锁目录不能是链接');const owner=stateRead(join(path,'owner.json'));if(owner&&!alive(owner.pid)){rmSync(path,{recursive:true});continue;}if(Date.now()>deadline)throw new Error('等待锁超时 '+name);await sleep(100);}}
17
+ try{return await fn();}finally{if(stateRead(join(path,'owner.json'))?.token===token)rmSync(path,{recursive:true});}
18
+ }
19
+ export function taskFile(root,taskId){id(taskId,'task');return join(root,'tasks',taskId+'.json');}
20
+ export function tasks(root){const dir=join(root,'tasks');return existsSync(dir)?readdirSync(dir).filter(x=>x.endsWith('.json')).map(x=>stateRead(join(dir,x))).filter(x=>x?.schema==='art-workshop/task'):[];}
21
+ export async function http(endpoint,path,{method='GET',body,timeout=10000}={}) {
22
+ const response=await fetch(new URL(path,endpoint),{method,signal:AbortSignal.timeout(timeout),...(body?{headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});
23
+ if(!response.ok){const content=await response.text(),error=new Error(`ComfyUI HTTP ${response.status}: ${content.slice(0,1000)}`);error.httpStatus=response.status;try{error.response=JSON.parse(content);}catch{};throw error;}
24
+ const content=await response.text();return content?JSON.parse(content):{};
25
+ }