@kevlns/art-workshop 0.5.1 → 0.6.0

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 (85) hide show
  1. package/AGENTS.md +25 -25
  2. package/LICENSE +21 -21
  3. package/README.md +65 -63
  4. package/art-workshop.mjs +219 -174
  5. package/docs/channels.md +49 -0
  6. package/docs/commands.md +2259 -22
  7. package/docs/configuration.md +90 -82
  8. package/docs/core-guidance.md +58 -50
  9. package/docs/data-formats.md +89 -85
  10. package/docs/deployment.md +32 -32
  11. package/docs/local-models/qwen-image-2.1.json +73 -73
  12. package/docs/local-models/qwen-image-2.1.md +33 -33
  13. package/docs/model-architecture.md +78 -78
  14. package/docs/modes.md +73 -67
  15. package/docs/release-0.6.0.md +9 -0
  16. package/lib/agent.mjs +32 -32
  17. package/lib/analysis-worker.mjs +36 -32
  18. package/lib/analyze.mjs +85 -85
  19. package/lib/asset-profile.mjs +23 -23
  20. package/lib/backends.mjs +2 -0
  21. package/lib/candidates.mjs +104 -103
  22. package/lib/channel-operation.mjs +84 -0
  23. package/lib/comfy-recovery.mjs +17 -17
  24. package/lib/conversation.mjs +77 -77
  25. package/lib/core.mjs +104 -75
  26. package/lib/deployment-guide.mjs +12 -12
  27. package/lib/design.mjs +29 -29
  28. package/lib/dimensions.mjs +22 -22
  29. package/lib/edit.mjs +43 -41
  30. package/lib/environment-operations.mjs +49 -49
  31. package/lib/environment-runtime.mjs +99 -99
  32. package/lib/environments.mjs +55 -55
  33. package/lib/executor.mjs +107 -107
  34. package/lib/generate.mjs +60 -58
  35. package/lib/generation-policy.mjs +1 -1
  36. package/lib/heartbeat.mjs +16 -16
  37. package/lib/images.mjs +1 -1
  38. package/lib/lifecycle.mjs +53 -53
  39. package/lib/migration.mjs +154 -154
  40. package/lib/object-format.mjs +1 -1
  41. package/lib/process-identity.mjs +22 -14
  42. package/lib/project.mjs +39 -39
  43. package/lib/prompt-structure.mjs +3 -3
  44. package/lib/refs.mjs +26 -26
  45. package/lib/runtime.mjs +25 -25
  46. package/lib/service.mjs +155 -126
  47. package/lib/settings.mjs +50 -50
  48. package/lib/shared.mjs +67 -67
  49. package/lib/style-bundle.mjs +98 -85
  50. package/lib/style-contract.mjs +74 -74
  51. package/lib/style-lifecycle.mjs +124 -125
  52. package/lib/style-review.mjs +14 -14
  53. package/lib/style-samples.mjs +92 -0
  54. package/lib/task-contract.mjs +94 -93
  55. package/lib/tasks.mjs +497 -497
  56. package/lib/templates.mjs +80 -80
  57. package/lib/video/PROVENANCE.json +63 -0
  58. package/lib/video/atomic.mjs +32 -0
  59. package/lib/video/channel.mjs +70 -0
  60. package/lib/video/contract-local-media.mjs +42 -0
  61. package/lib/video/contract-story.mjs +213 -0
  62. package/lib/video/contract-video.mjs +117 -0
  63. package/lib/video/contracts.mjs +3 -0
  64. package/lib/video/h3.mjs +232 -0
  65. package/lib/video/local-runtime.mjs +20 -0
  66. package/lib/video/media.mjs +223 -0
  67. package/lib/video/models.mjs +336 -0
  68. package/lib/video/path.mjs +18 -0
  69. package/lib/video/process.mjs +15 -0
  70. package/lib/video/resource.mjs +15 -0
  71. package/lib/video/service.mjs +731 -0
  72. package/lib/video/workflow.mjs +571 -0
  73. package/lib/video.mjs +12 -0
  74. package/lib/vision.mjs +56 -56
  75. package/lib/worker-process.mjs +6 -6
  76. package/lib/workspace.mjs +305 -292
  77. package/package.json +8 -3
  78. package/rules/core-guidance.json +22 -22
  79. package/skills/art-workshop/SKILL.md +19 -17
  80. package/skills/art-workshop/references/conversation.md +11 -11
  81. package/skills/art-workshop/references/expression.md +27 -27
  82. package/skills/art-workshop/references/project.md +119 -109
  83. package/skills/art-workshop/references/style-discussion.md +7 -3
  84. package/skills/art-workshop/references/video.md +13 -0
  85. package/v-cli.plugin.json +7240 -2747
@@ -1,125 +1,124 @@
1
- import {assertObjectCurrent} from './workspace.mjs';
2
- import {styleProvenance} from './style-evidence.mjs';
3
- import {join} from 'node:path';
4
- import {randomUUID} from 'node:crypto';
5
- import {existsSync,openSync,closeSync,rmSync,cpSync,mkdirSync} from 'node:fs';
6
- import {spawn} from 'node:child_process';
7
- import {fileURLToPath} from 'node:url';
8
- import {readObject,verifyReferences,ownedPath,objectFile,objectDirectory} from './workspace.mjs';
9
- import {runtimeRoot,tasks,locked,taskFile,alive,stateRead} from './runtime.mjs';
10
- import {taskStatus,taskView} from './tasks.mjs';
11
- import {assertIdle} from './lifecycle.mjs';
12
- import {writeJson,readJson,hash} from './shared.mjs';
13
- import {analyzeStyle} from './analyze.mjs';
14
- import {referenceInput,analyzeTaskReferences} from './task-references.mjs';
15
- import {freezeCore,validateReport} from './core.mjs';
16
- import {styleReviewState,issueFingerprint,validateIssues,resolvedRecommendation,validateStyleConfig,styleSourceHash,styleEvidenceHash} from './style-review.mjs';
17
- import {mutateObject} from './workspace.mjs';
18
- import {REFERENCE_CATEGORIES} from './style-contract.mjs';
19
-
20
- export function analysisInput(settings,record){
21
- const scopes=Object.fromEntries(REFERENCE_CATEGORIES.map(c=>[c.directory,c.scope]));
22
- return {project:record.project,id:record.id,description:record.config.description??'', constraints:record.config.constraints??[],...(record.config.rules?{rules:record.config.rules}:{}),previous:record.report?.data??null,refs:verifyReferences(settings.paths.workspace,record).map(ref=>{if(!scopes[ref.category])throw new Error('参考分类已取消,请先明确重新分类:'+ref.id);return {path:ref.path,scope:scopes[ref.category],note:ref.note||ref.category,ignore:ref.ignore??''};})};
23
- }
24
-
25
- /** User-authored rules reuse unchanged evidence; this is not a model analysis. */
26
- export async function reviseStyleRules(settings,projectId,styleId,revision,{rules,summary,note}={}){
27
- return mutateObject(settings,projectId,'style',styleId,revision,record=>{
28
- validateStyleConfig({rules});
29
- if(typeof summary!=='string'||!summary.trim()||summary.length>300)throw new Error('风格概述须为1至300字');
30
- if(typeof note!=='string'||!note.trim()||note.length>2000)throw new Error('请记录本次规则修改的用户依据');
31
- const prior=record.report;
32
- if(!prior)throw new Error('缺少可沿用的参考证据,请先分析');
33
- validateReport(prior.data,projectId);verifyReferences(settings.paths.workspace,record);
34
- if(prior.evidenceHash?prior.evidenceHash!==styleEvidenceHash(record):prior.sourceHash!==styleSourceHash(record))throw new Error('参考证据已变化,请重新分析;不能只修改规则沿用旧证据');
35
- if(!styleReviewState({...record,report:{...prior,sourceHash:styleSourceHash(record)}}).ready)throw new Error('仍有未确认的取舍,请先处理当前问题');
36
- if(prior.sourceHash===styleSourceHash(record)&&prior.data.provenance?.method==='user-rules'&&prior.data.summary===summary.trim()&&hash(prior.data.recommendation.rules)===hash(rules))return record;
37
- record.reviewHistory??=[];
38
- record.reviewHistory.push({type:'rules-revision',revision:record.revision+1,note:note.trim(),previousReport:structuredClone(prior)});
39
- record.config={...record.config,rules:structuredClone(rules)};
40
- const data={...structuredClone(prior.data),id:styleId,summary:summary.trim(),recommendation:{rules:structuredClone(rules)},issues:[],decisions:[],provenance:styleProvenance(prior.data.provenance,{method:'user-rules',sourceReportHash:hash(prior.data),note:note.trim()})};
41
- validateReport(data,projectId);
42
- record.report={data,sourceRevision:record.revision+1,sourceHash:styleSourceHash(record),evidenceHash:styleEvidenceHash(record),path:null,runId:null};
43
- return record;
44
- });
45
- }
46
- export async function startAnalysis(settings,projectId,styleId,revision,{dry=false,kind='style',operationId=null}={}){
47
- const root=runtimeRoot(settings);
48
- const prepare=async()=>{
49
- if(operationId&&!dry){if(!/^[a-z0-9-]{1,128}$/.test(operationId))throw new Error('操作身份非法');const existing=tasks(root).filter(t=>t.operationId===operationId);if(existing.length){if(existing.length!==1||existing[0].project!==projectId||existing[0].objectKind!==kind||existing[0].objectId!==styleId||existing[0].sourceRevision!==revision)throw new Error('操作身份已用于其他分析请求');return taskView(taskStatus(root,existing[0].taskId));}}
50
- const record=readObject(settings.paths.workspace,projectId,kind,styleId);
51
- assertObjectCurrent(settings.paths.workspace,record);
52
- if(record.revision!==revision)throw new Error('风格版本冲突');if(record.status!=='draft')throw new Error('只有可编辑对象可分析');
53
- const input=kind==='style'?analysisInput(settings,record):referenceInput(settings.paths.workspace,record),analyzer=kind==='style'?analyzeStyle:analyzeTaskReferences,preview=await analyzer({projectId,input,root:settings.paths.workspace,refsDir:settings.paths.workspace,analysisModel:record.config.analysis?.model??record.config.model??settings.analysisModel,dry:true});
54
- if(dry)return preview;
55
- assertIdle(tasks(root).filter(t=>(kind==='style'?t.styleId===styleId&&t.project===projectId:t.plan?.job===styleId&&t.plan?.project===projectId||t.objectId===styleId&&t.project===projectId)).map(t=>taskStatus(root,t.taskId)),'风格');
56
- const gate=stateRead(join(root,'shutdown.json'));if(gate&&alive(gate.pid))throw new Error('服务正在关闭,不能启动分析');
57
- const taskId='task-'+randomUUID(),file=taskFile(root,taskId),logPath=join(root,'tasks',taskId+'.log');
58
- const evidence=ownedPath(objectDirectory(settings.paths.workspace,projectId,kind,styleId),'reports',taskId,'refs');
59
- for(const [index,ref] of (input.refs??input.references).entries()){mkdirSync(evidence,{recursive:true});const destination=ownedPath(evidence,index+'-'+ref.path.split(/[\\/]/).at(-1));cpSync(ref.path,destination,{errorOnExist:true,force:false});ref.path=destination;}
60
- const task={schema:'art-workshop/task',operationId,kind:kind==='style'?'style-analysis':'task-reference-analysis',objectKind:kind,objectId:styleId,taskId,project:projectId,...(kind==='style'?{styleId}:{}),status:'queued',stopConfirmed:false,createdAt:new Date().toISOString(),sourceRevision:revision,sourceHash:hash({config:record.config,references:record.references}),input,model:preview.provenance.model,analysisProvider:preview.provenance.provider,workspace:settings.paths.workspace,cache:settings.paths.cache,root,logPath};writeJson(file,task);
61
- const fd=openSync(logPath,'a'),child=spawn(process.execPath,[fileURLToPath(new URL('./analysis-worker.mjs',import.meta.url)),file],{detached:true,windowsHide:true,stdio:['ignore',fd,fd]});closeSync(fd);
62
- try{await new Promise((resolve,reject)=>{child.once('spawn',resolve);child.once('error',reject);});}catch(error){task.status='failed';task.stopConfirmed=true;task.error=error.message;writeJson(file,task);throw error;}
63
- child.unref();return {taskId,status:'queued',styleId,sourceRevision:revision};
64
- };
65
- return dry?prepare():locked(root,'control',prepare);
66
- }
67
- export async function adoptStyle(settings,projectId,styleId,revision,{note}={}){
68
- return locked(runtimeRoot(settings),'control',async()=>{
69
- const record=readObject(settings.paths.workspace,projectId,'style',styleId);
70
- if(record.status!=='draft'||record.revision!==revision)throw new Error('风格状态或版本已变化');
71
- assertIdle(tasks(runtimeRoot(settings)).filter(t=>t.styleId===styleId&&t.project===projectId).map(t=>taskStatus(runtimeRoot(settings),t.taskId)),'风格');
72
- verifyReferences(settings.paths.workspace,record);
73
- if(!record.report||record.report.sourceHash!==hash({config:record.config,references:record.references}))throw new Error('分析报告缺失或已过期');
74
- const report=record.report.data;validateReport(report,projectId);if(report.id!==styleId||!styleReviewState(record).ready)throw new Error('报告身份、版本或待决定问题尚未解决');
75
- const journal=ownedPath(objectDirectory(settings.paths.workspace,projectId,'style',styleId),'adoption.json');
76
- writeJson(journal,{project:projectId,styleId,revision,report,note,record,createdAt:new Date().toISOString()});
77
- const core=freezeCore({projectId,report,root:settings.paths.workspace,note,history:record.reviewHistory??[]});
78
- if(record.migration?.status==='ready')record.migration.confirmedAt??=new Date().toISOString();
79
- record.status='frozen';record.coreHash=core.coreHash;record.revision++;record.updatedAt=new Date().toISOString();
80
- try{writeJson(objectFile(settings.paths.workspace,projectId,'style',styleId),record);}catch(error){throw new Error('核心已冻结,但风格状态提交失败,需要恢复:'+error.message);}
81
- rmSync(journal,{force:true});return record;
82
- });
83
- }
84
-
85
-
86
- /** Complete an already authorized adoption after a crash; never create a second core. */
87
- export async function recoverStyleAdoption(settings,projectId,styleId){
88
- return locked(runtimeRoot(settings),'control',async()=>{
89
- const directory=objectDirectory(settings.paths.workspace,projectId,'style',styleId),journal=ownedPath(directory,'adoption.json');
90
- if(!existsSync(journal))return readObject(settings.paths.workspace,projectId,'style',styleId);
91
- const intent=readJson(journal);if(intent.project!==projectId||intent.styleId!==styleId)throw new Error('恢复事务身份不匹配');
92
- const file=objectFile(settings.paths.workspace,projectId,'style',styleId),record=readJson(file);
93
- if(record.revision!==intent.revision&&!(record.revision===intent.revision+1&&record.status==='frozen'))throw new Error('风格版本与恢复事务冲突');
94
- const corePath=ownedPath(directory,'core.json');
95
- let core;if(existsSync(corePath)){core=readJson(corePath);const {coreHash,...body}=core;if(hash(body)!==coreHash||core.id!==styleId||hash(core.report)!==hash(intent.report))throw new Error('已有核心与恢复事务不匹配');}
96
- else core=freezeCore({projectId,report:intent.report,root:settings.paths.workspace,note:intent.note,history:intent.record.reviewHistory??[]});
97
- const projectFile=ownedPath(settings.paths.workspace,'projects',projectId,'project.json'),project=readJson(projectFile);
98
- if(!project.cores.includes(styleId)){project.cores.push(styleId);project.defaultCore??=styleId;project.revision++;writeJson(projectFile,project);}
99
- if(record.migration?.status==='ready')record.migration.confirmedAt??=core.approvedAt;
100
- record.status='frozen';record.coreHash=core.coreHash;record.revision=intent.revision+1;record.updatedAt=core.approvedAt;writeJson(file,record);rmSync(journal,{force:true});return record;
101
- });
102
- }
103
-
104
- /** Explicit decisions update the review, never rewrite reference evidence or raw model output. */
105
- export async function resolveStyleIssue(settings,projectId,styleId,revision,{issueId,optionId,note}={}){
106
- return mutateObject(settings,projectId,'style',styleId,revision,record=>{
107
- const state=styleReviewState(record);
108
- if(state.stale||!record.report)throw new Error(state.reason);
109
- validateReport(record.report.data,projectId);
110
- const report=record.report.data,issue=report.issues.find(i=>i.id===issueId);
111
- const option=issue?.options.find(o=>o.id===optionId);
112
- if(!issue||!option)throw new Error('问题或选项不存在,请重新读取');
113
- if(typeof note!=='string'||!note.trim()||note.length>2000)throw new Error('必须记录用户取舍依据');
114
- const touched=new Set([...option.remove,...option.upsert.map(r=>r.id)]);
115
- report.decisions=report.decisions.filter(d=>{
116
- if(d.issueId===issueId)return false;
117
- const old=report.issues.find(i=>i.id===d.issueId)?.options.find(o=>o.id===d.optionId);
118
- return old&&![...old.remove,...old.upsert.map(r=>r.id)].some(id=>touched.has(id));
119
- });
120
- report.decisions.push({issueId,fingerprint:issueFingerprint(issue),optionId,note:note.trim(),decidedAt:new Date().toISOString()});
121
- validateIssues(report);resolvedRecommendation(report);
122
- record.reviewHistory??=[];record.reviewHistory.push({revision:record.revision+1,runId:record.report.runId,decision:report.decisions.at(-1)});
123
- return record;
124
- });
125
- }
1
+ import {assertObjectCurrent} from './workspace.mjs';
2
+ import {styleProvenance} from './style-evidence.mjs';
3
+ import {join} from 'node:path';
4
+ import {randomUUID} from 'node:crypto';
5
+ import {existsSync,openSync,closeSync,rmSync,cpSync,mkdirSync} from 'node:fs';
6
+ import {spawn} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {readObject,verifyReferences,ownedPath,objectFile,objectDirectory} from './workspace.mjs';
9
+ import {runtimeRoot,tasks,locked,taskFile,alive,stateRead} from './runtime.mjs';
10
+ import {taskStatus,taskView} from './tasks.mjs';
11
+ import {assertIdle} from './lifecycle.mjs';
12
+ import {writeJson,readJson,hash} from './shared.mjs';
13
+ import {analyzeStyle} from './analyze.mjs';
14
+ import {referenceInput,analyzeTaskReferences} from './task-references.mjs';
15
+ import {freezeCore,validateReport} from './core.mjs';
16
+ import {styleReviewState,issueFingerprint,validateIssues,resolvedRecommendation,validateStyleConfig,styleSourceHash,styleEvidenceHash} from './style-review.mjs';
17
+ import {mutateObject} from './workspace.mjs';
18
+ import {REFERENCE_CATEGORIES} from './style-contract.mjs';
19
+
20
+ export function analysisInput(settings,record){
21
+ const scopes=Object.fromEntries(REFERENCE_CATEGORIES.map(c=>[c.directory,c.scope]));
22
+ return {project:record.project,id:record.id,description:record.config.description??'', constraints:record.config.constraints??[],...(record.config.rules?{rules:record.config.rules}:{}),previous:record.report?.data??null,refs:verifyReferences(settings.paths.workspace,record).map(ref=>{if(!scopes[ref.category])throw new Error('参考分类已取消,请先明确重新分类:'+ref.id);return {path:ref.path,scope:scopes[ref.category],note:ref.note||ref.category,ignore:ref.ignore??''};})};
23
+ }
24
+
25
+ /** Explicit rule edits are saved immediately; reference analysis remains historical evidence. */
26
+ export async function reviseStyleRules(settings,projectId,styleId,revision,{rules,summary,note}={}){
27
+ return mutateObject(settings,projectId,'style',styleId,revision,record=>{
28
+ validateStyleConfig({rules});
29
+ if(typeof summary!=='string'||!summary.trim()||summary.length>300)throw new Error('风格概述须为1至300字');
30
+ if(typeof note!=='string'||!note.trim()||note.length>2000)throw new Error('请记录本次规则修改的用户依据');
31
+ const prior=record.report;
32
+ if(prior?.sourceHash===styleSourceHash(record)&&prior.data.provenance?.method==='user-rules'&&prior.data.summary===summary.trim()&&hash(prior.data.recommendation.rules)===hash(rules))return record;
33
+ record.reviewHistory??=[];
34
+ record.reviewHistory.push({type:'rules-revision',revision:record.revision+1,note:note.trim(),previousReport:structuredClone(prior)});
35
+ record.config={...record.config,rules:structuredClone(rules)};
36
+ const data={schema:'art-workshop/style-report',schemaVersion:3,project:projectId,observations:[],notes:[],...structuredClone(prior?.data??{}),id:styleId,summary:summary.trim(),recommendation:{rules:structuredClone(rules)},issues:[],decisions:[],provenance:styleProvenance(prior?.data?.provenance,{method:'user-rules',...(prior?{sourceReportHash:hash(prior.data)}:{}),note:note.trim()})};
37
+ validateReport(data,projectId);
38
+ record.report={data,sourceRevision:record.revision+1,sourceHash:styleSourceHash(record),evidenceHash:styleEvidenceHash(record),path:null,runId:null};
39
+ return record;
40
+ });
41
+ }
42
+ export async function startAnalysis(settings,projectId,styleId,revision,{dry=false,kind='style',operationId=null}={}){
43
+ const root=runtimeRoot(settings);
44
+ const prepare=async()=>{
45
+ if(operationId&&!dry){if(!/^[a-z0-9-]{1,128}$/.test(operationId))throw new Error('操作身份非法');const existing=tasks(root).filter(t=>t.operationId===operationId);if(existing.length){if(existing.length!==1||existing[0].project!==projectId||existing[0].objectKind!==kind||existing[0].objectId!==styleId||existing[0].sourceRevision!==revision)throw new Error('操作身份已用于其他分析请求');return taskView(taskStatus(root,existing[0].taskId));}}
46
+ const record=readObject(settings.paths.workspace,projectId,kind,styleId);
47
+ assertObjectCurrent(settings.paths.workspace,record);
48
+ if(record.revision!==revision)throw new Error('风格版本冲突');if(!['draft','frozen'].includes(record.status)||kind==='task'&&record.status!=='draft')throw new Error('只有可编辑对象可分析');
49
+ const input=kind==='style'?analysisInput(settings,record):referenceInput(settings.paths.workspace,record),analyzer=kind==='style'?analyzeStyle:analyzeTaskReferences,preview=await analyzer({projectId,input,root:settings.paths.workspace,refsDir:settings.paths.workspace,analysisModel:record.config.analysis?.model??record.config.model??settings.analysisModel,dry:true});
50
+ if(dry)return preview;
51
+ assertIdle(tasks(root).filter(t=>(kind==='style'?t.styleId===styleId&&t.project===projectId:t.plan?.job===styleId&&t.plan?.project===projectId||t.objectId===styleId&&t.project===projectId)).map(t=>taskStatus(root,t.taskId)),'风格');
52
+ const gate=stateRead(join(root,'shutdown.json'));if(gate&&alive(gate.pid))throw new Error('服务正在关闭,不能启动分析');
53
+ const taskId='task-'+randomUUID(),file=taskFile(root,taskId),logPath=join(root,'tasks',taskId+'.log');
54
+ const evidence=ownedPath(objectDirectory(settings.paths.workspace,projectId,kind,styleId),'reports',taskId,'refs');
55
+ for(const [index,ref] of (input.refs??input.references).entries()){mkdirSync(evidence,{recursive:true});const destination=ownedPath(evidence,index+'-'+ref.path.split(/[\\/]/).at(-1));cpSync(ref.path,destination,{errorOnExist:true,force:false});ref.path=destination;}
56
+ const task={schema:'art-workshop/task',operationId,kind:kind==='style'?'style-analysis':'task-reference-analysis',objectKind:kind,objectId:styleId,taskId,project:projectId,...(kind==='style'?{styleId}:{}),status:'queued',stopConfirmed:false,createdAt:new Date().toISOString(),sourceRevision:revision,sourceHash:hash({config:record.config,references:record.references}),input,model:preview.provenance.model,analysisProvider:preview.provenance.provider,workspace:settings.paths.workspace,cache:settings.paths.cache,root,logPath};writeJson(file,task);
57
+ const fd=openSync(logPath,'a'),child=spawn(process.execPath,[fileURLToPath(new URL('./analysis-worker.mjs',import.meta.url)),file],{detached:true,windowsHide:true,stdio:['ignore',fd,fd]});closeSync(fd);
58
+ try{await new Promise((resolve,reject)=>{child.once('spawn',resolve);child.once('error',reject);});}catch(error){task.status='failed';task.stopConfirmed=true;task.error=error.message;writeJson(file,task);throw error;}
59
+ child.unref();return {taskId,status:'queued',styleId,sourceRevision:revision};
60
+ };
61
+ return dry?prepare():locked(root,'control',prepare);
62
+ }
63
+ export async function adoptStyle(settings,projectId,styleId,revision,{note}={}){
64
+ return locked(runtimeRoot(settings),'control',async()=>{
65
+ const record=readObject(settings.paths.workspace,projectId,'style',styleId);
66
+ if(!['draft','frozen'].includes(record.status)||record.revision!==revision)throw new Error('风格状态或版本已变化');
67
+ if(record.status==='frozen'&&Array.isArray(record.config.rules))return record;
68
+ assertIdle(tasks(runtimeRoot(settings)).filter(t=>t.styleId===styleId&&t.project===projectId).map(t=>taskStatus(runtimeRoot(settings),t.taskId)),'风格');
69
+ verifyReferences(settings.paths.workspace,record);
70
+ if(!record.report||record.report.sourceHash!==hash({config:record.config,references:record.references}))throw new Error('分析报告缺失或已过期');
71
+ const report=record.report.data;validateReport(report,projectId);if(report.id!==styleId||!styleReviewState(record).ready)throw new Error('报告身份、版本或待决定问题尚未解决');
72
+ const journal=ownedPath(objectDirectory(settings.paths.workspace,projectId,'style',styleId),'adoption.json');
73
+ writeJson(journal,{project:projectId,styleId,revision,report,note,record,createdAt:new Date().toISOString()});
74
+ const core=freezeCore({projectId,report,root:settings.paths.workspace,note,history:record.reviewHistory??[]});
75
+ record.config.rules=structuredClone(core.config.rules);record.report.sourceHash=hash({config:record.config,references:record.references});
76
+ if(record.migration?.status==='ready')record.migration.confirmedAt??=new Date().toISOString();
77
+ record.status='frozen';record.coreHash=core.coreHash;record.revision++;record.updatedAt=new Date().toISOString();
78
+ try{writeJson(objectFile(settings.paths.workspace,projectId,'style',styleId),record);}catch(error){throw new Error('核心已冻结,但风格状态提交失败,需要恢复:'+error.message);}
79
+ rmSync(journal,{force:true});return record;
80
+ });
81
+ }
82
+
83
+
84
+ /** Complete an already authorized adoption after a crash; never create a second core. */
85
+ export async function recoverStyleAdoption(settings,projectId,styleId){
86
+ return locked(runtimeRoot(settings),'control',async()=>{
87
+ const directory=objectDirectory(settings.paths.workspace,projectId,'style',styleId),journal=ownedPath(directory,'adoption.json');
88
+ if(!existsSync(journal))return readObject(settings.paths.workspace,projectId,'style',styleId);
89
+ const intent=readJson(journal);if(intent.project!==projectId||intent.styleId!==styleId)throw new Error('恢复事务身份不匹配');
90
+ const file=objectFile(settings.paths.workspace,projectId,'style',styleId),record=readJson(file);
91
+ if(record.revision!==intent.revision&&!(record.revision===intent.revision+1&&record.status==='frozen'))throw new Error('风格版本与恢复事务冲突');
92
+ const corePath=ownedPath(directory,'core.json');
93
+ let core;if(existsSync(corePath)){core=readJson(corePath);const {coreHash,...body}=core;if(hash(body)!==coreHash||core.id!==styleId||hash(core.report)!==hash(intent.report))throw new Error('已有核心与恢复事务不匹配');}
94
+ else core=freezeCore({projectId,report:intent.report,root:settings.paths.workspace,note:intent.note,history:intent.record.reviewHistory??[]});
95
+ const projectFile=ownedPath(settings.paths.workspace,'projects',projectId,'project.json'),project=readJson(projectFile);
96
+ if(!project.cores.includes(styleId)){project.cores.push(styleId);project.defaultCore??=styleId;project.revision++;writeJson(projectFile,project);}
97
+ if(record.migration?.status==='ready')record.migration.confirmedAt??=core.approvedAt;
98
+ record.status='frozen';record.coreHash=core.coreHash;record.revision=intent.revision+1;record.updatedAt=core.approvedAt;writeJson(file,record);rmSync(journal,{force:true});return record;
99
+ });
100
+ }
101
+
102
+ /** Explicit decisions update the review, never rewrite reference evidence or raw model output. */
103
+ export async function resolveStyleIssue(settings,projectId,styleId,revision,{issueId,optionId,note}={}){
104
+ return mutateObject(settings,projectId,'style',styleId,revision,record=>{
105
+ const state=styleReviewState(record);
106
+ if(state.stale||!record.report)throw new Error(state.reason);
107
+ validateReport(record.report.data,projectId);
108
+ const report=record.report.data,issue=report.issues.find(i=>i.id===issueId);
109
+ const option=issue?.options.find(o=>o.id===optionId);
110
+ if(!issue||!option)throw new Error('问题或选项不存在,请重新读取');
111
+ if(typeof note!=='string'||!note.trim()||note.length>2000)throw new Error('必须记录用户取舍依据');
112
+ const touched=new Set([...option.remove,...option.upsert.map(r=>r.id)]);
113
+ report.decisions=report.decisions.filter(d=>{
114
+ if(d.issueId===issueId)return false;
115
+ const old=report.issues.find(i=>i.id===d.issueId)?.options.find(o=>o.id===d.optionId);
116
+ return old&&![...old.remove,...old.upsert.map(r=>r.id)].some(id=>touched.has(id));
117
+ });
118
+ report.decisions.push({issueId,fingerprint:issueFingerprint(issue),optionId,note:note.trim(),decidedAt:new Date().toISOString()});
119
+ validateIssues(report);resolvedRecommendation(report);
120
+ if(Array.isArray(record.config.rules)){record.config.rules=structuredClone(resolvedRecommendation(report).rules);record.report.sourceHash=styleSourceHash(record);}
121
+ record.reviewHistory??=[];record.reviewHistory.push({revision:record.revision+1,runId:record.report.runId,decision:report.decisions.at(-1)});
122
+ return record;
123
+ });
124
+ }
@@ -1,14 +1,14 @@
1
- import {hash} from './shared.mjs';
2
- import {STYLE_SCHEMA_VERSION} from './style-contract.mjs';
3
- import {inspectStyleReport,unresolvedIssues,resolvedRecommendation} from './style-report.mjs';
4
- export {validateStyleConfig} from './style-contract.mjs';
5
- export {issueFingerprint,validateIssues,applyOption,unresolvedIssues,resolvedRecommendation} from './style-report.mjs';
6
- export function styleSourceHash(record){return hash({config:record.config,references:record.references});}
7
- export function styleEvidenceHash(record){return hash({references:record.references,analysis:record.config.analysis??null});}
8
- export function styleReviewState(record){
9
- if(!record.report)return {ready:false,stale:false,openIssues:[],reason:'请先生成风格报告'};
10
- if(record.report.data?.schemaVersion!==STYLE_SCHEMA_VERSION)return {ready:false,stale:true,openIssues:[],reason:'历史报告已保留,请生成新版风格报告'};
11
- const validity=inspectStyleReport(record.report.data,{project:record.project,id:record.id});if(!validity.valid)return {ready:false,stale:true,openIssues:[],reason:validity.reason};
12
- const stale=record.report.sourceHash!==styleSourceHash(record),openIssues=unresolvedIssues(record.report.data).map(i=>i.id);
13
- return {ready:!stale&&!openIssues.length,stale,openIssues,recommendation:resolvedRecommendation(record.report.data),reason:stale?'草稿或参考已修改,请复核报告':openIssues.length?`还有 ${openIssues.length} 项待决定;确认取舍后即可采用`:'风格方案已就绪,可确认采用'};
14
- }
1
+ import {hash} from './shared.mjs';
2
+ import {STYLE_SCHEMA_VERSION} from './style-contract.mjs';
3
+ import {inspectStyleReport,unresolvedIssues,resolvedRecommendation} from './style-report.mjs';
4
+ export {validateStyleConfig} from './style-contract.mjs';
5
+ export {issueFingerprint,validateIssues,applyOption,unresolvedIssues,resolvedRecommendation} from './style-report.mjs';
6
+ export function styleSourceHash(record){return hash({config:record.config,references:record.references});}
7
+ export function styleEvidenceHash(record){return hash({references:record.references,analysis:record.config.analysis??null});}
8
+ export function styleReviewState(record){
9
+ if(!record.report)return {ready:false,stale:false,openIssues:[],reason:'请先生成风格报告'};
10
+ if(record.report.data?.schemaVersion!==STYLE_SCHEMA_VERSION)return {ready:false,stale:true,openIssues:[],reason:'历史报告已保留,请生成新版风格报告'};
11
+ const validity=inspectStyleReport(record.report.data,{project:record.project,id:record.id});if(!validity.valid)return {ready:false,stale:true,openIssues:[],reason:validity.reason};
12
+ const stale=record.report.sourceHash!==styleSourceHash(record),openIssues=unresolvedIssues(record.report.data).map(i=>i.id);
13
+ return {ready:!stale&&!openIssues.length,stale,openIssues,recommendation:resolvedRecommendation(record.report.data),reason:stale?'草稿或参考已修改,请复核报告':openIssues.length?`还有 ${openIssues.length} 项待决定;确认取舍后即可采用`:'风格方案已就绪,可确认采用'};
14
+ }
@@ -0,0 +1,92 @@
1
+ import {existsSync,mkdirSync,readFileSync,writeFileSync,rmSync} from 'node:fs';
2
+ import {dirname} from 'node:path';
3
+ import {hash,integer} from './shared.mjs';
4
+ import {createHash} from 'node:crypto';
5
+ import {readObject,objectDirectory,ownedPath,mutateObject,createObject,assertObjectCurrent} from './workspace.mjs';
6
+ import {loadCore} from './core.mjs';
7
+ import {jobTemplate} from './templates.mjs';
8
+ import {candidates} from './candidates.mjs';
9
+ import {tasks,runtimeRoot,locked} from './runtime.mjs';
10
+ import {validateImage} from './images.mjs';
11
+ import {sha256File} from './bl.mjs';
12
+
13
+ export const styleRulesHash=core=>hash(core.config.rules);
14
+
15
+ /** Original analysis references never enter generation. Only independently copied, approved samples do. */
16
+ export function styleSampleInputs(root,projectId,core,mode='approved'){
17
+ if(!['approved','text-only'].includes(mode))throw new Error('styleReferenceMode 必须为 approved 或 text-only');
18
+ const all=core?.approvedSamples??[],rulesHash=core?styleRulesHash(core):null;
19
+ const current=all.filter(sample=>sample.rulesHash===rulesHash),staleCount=all.length-current.length;
20
+ const selection={mode,status:mode==='text-only'?'text-only':current.length?'approved':'no-samples',rulesHash,staleCount,samples:[]};
21
+ if(mode==='text-only'||!core)return {selection,refs:[],prompt:''};
22
+ if(all.length&&!current.length)throw new Error('风格规则已更新,运行时参考均待复核;请重新打样并定版,或明确选择 text-only 仅规则生成');
23
+ const directory=objectDirectory(root,projectId,'style',core.id);
24
+ const refs=current.map(sample=>{
25
+ const path=ownedPath(directory,sample.path);
26
+ if(!existsSync(path)||sha256File(path)!==sample.hash)throw new Error('运行时参考缺失或已改变:'+sample.id);
27
+ selection.samples.push({id:sample.id,hash:sample.hash,rulesHash:sample.rulesHash,note:sample.note??''});
28
+ return {path,hash:sample.hash};
29
+ });
30
+ return {selection,refs,prompt:refs.length?'【定版样张:运行时风格参考】\n输入图片仅作为绘制语言的视觉参考。借鉴媒介、描边、明暗组织、笔触、刻画密度与色彩关系;不要沿用参考图片的具体主体、结构、身份色、姿态、构图、背景或画面文字。本次任务定义实际内容,规则中的明确要求与适用条件继续有效。\n'+current.map((s,i)=>`运行时参考 ${i+1}${s.note?':'+s.note:''}`).join('\n'):''};
31
+ }
32
+
33
+ export async function createStyleSampleJob(settings,projectId,styleId,revision,{name,count=1}={}){
34
+ integer(count,'count',1,4);
35
+ return locked(runtimeRoot(settings),'control',async()=>{
36
+ const style=readObject(settings.paths.workspace,projectId,'style',styleId);
37
+ assertObjectCurrent(settings.paths.workspace,style);
38
+ if(style.revision!==revision)throw new Error('对象版本冲突,请重新读取');
39
+ if(['discarded','cleanup-required'].includes(style.status))throw new Error('风格不可用于打样');
40
+ const core=loadCore(projectId,styleId,settings.paths.workspace);
41
+ const config=jobTemplate(settings.paths.workspace,projectId,{core:styleId});
42
+ config.styleReferenceMode='text-only';
43
+ config.execution={...config.execution,perValue:count};
44
+ if(style.config.analysis)config.analysis=structuredClone(style.config.analysis);
45
+ const subjects=[['stone','石块','一块不规则岩石,轮廓完整,具有几个清楚的大切面','中性灰'],['wood-box','木箱','一个简单方形木箱,保留木板接缝与金属包角','暖棕色木板、深灰色金属'],['metal-pot','金属壶','一把带把手和壶嘴的金属壶,结构清楚','低饱和蓝色壶体、银色金属边缘']];
46
+ config.items=subjects.map(([id,kind,appearance,color])=>({...structuredClone(config.items[0]),id,intent:`风格验证样张:${kind}。展示当前规则组合后的画法,保持主体简单完整,便于比较描边、明暗、笔触与材质表现`,entities:[{id:'subject',kind:id,appearance,color,role:'primary',count:1}],mustRead:['完整轮廓','保持主体结构与身份色','用同一绘制语言呈现']}));
47
+ return createObject(settings,projectId,'task',{name:name?.trim()||style.name+' · 风格打样',config,source:{kind:'style-sample',styleId,revision:style.revision,count,rulesHash:styleRulesHash(core),coreHash:core.coreHash}});
48
+ });
49
+ }
50
+
51
+ export async function selectStyleSample(settings,projectId,styleId,revision,{job,run,candidate,note=''}={}){
52
+ if(typeof note!=='string'||note.length>2000)throw new Error('运行时参考说明须为2000字以内文本');
53
+ let created;
54
+ try{return await mutateObject(settings,projectId,'style',styleId,revision,async record=>{
55
+ const core=loadCore(projectId,styleId,settings.paths.workspace),rulesHash=styleRulesHash(core);
56
+ const execution=tasks(runtimeRoot(settings)).find(t=>t.taskId===run);
57
+ if(execution?.plan?.project!==projectId||execution.plan.job!==job||execution.plan.sources.core!==styleId)throw new Error('候选必须来自使用当前风格的项目任务');
58
+ if(styleRulesHash(execution.plan.snapshots.core)!==rulesHash)throw new Error('候选使用的风格规则已变化,请按当前规则重新打样');
59
+ const chosen=candidates(settings,projectId,job,run).find(c=>c.candidateId===candidate&&c.accepted&&c.editable&&!c.deleted);
60
+ if(!chosen)throw new Error('运行时参考必须是已停止批次中完整、有效的成功候选');
61
+ const bytes=readFileSync(chosen.path),contentHash=createHash('sha256').update(bytes).digest('hex');
62
+ if(contentHash!==chosen.hash)throw new Error('候选图片已改变,不能设为运行时参考');
63
+ const image=await validateImage(bytes);
64
+ record.samples??=[];
65
+ const duplicates=record.samples.filter(sample=>sample.hash===contentHash),existing=duplicates.find(sample=>sample.rulesHash===rulesHash)??duplicates[0];
66
+ if(existing){
67
+ const file=ownedPath(objectDirectory(settings.paths.workspace,projectId,'style',styleId),existing.path);
68
+ if(!existsSync(file)||sha256File(file)!==contentHash)throw new Error('保留的运行时参考缺失或已改变,不能覆盖历史参考');
69
+ if(existing.rulesHash===rulesHash&&duplicates.length===1)return record;
70
+ const updated=existing.rulesHash===rulesHash?existing:{...existing,rulesHash,jobId:job,runId:run,candidateId:candidate,itemId:chosen.itemId,note:note.trim()||existing.note||'',validatedAt:new Date().toISOString(),model:execution.plan.backend?.model??execution.plan.execution.model,backend:execution.plan.backend?.id??null};
71
+ record.samples=record.samples.flatMap(sample=>sample.id===existing.id?[updated]:sample.hash===contentHash?[]:[sample]);
72
+ return record;
73
+ }
74
+ if(record.samples.length>=12)throw new Error('运行时参考最多12张,请先移除不再使用的参考');
75
+ const sampleId='sample-'+contentHash.slice(0,24);
76
+ const path='samples/'+sampleId+'.'+(image.format==='jpeg'?'jpg':image.format),destination=ownedPath(objectDirectory(settings.paths.workspace,projectId,'style',styleId),path);
77
+ mkdirSync(dirname(destination),{recursive:true});
78
+ if(existsSync(destination)){if(sha256File(destination)!==contentHash)throw new Error('保留的运行时参考已改变,不能覆盖历史参考');}
79
+ else {writeFileSync(destination,bytes,{flag:'wx'});created=destination;}
80
+ record.samples.push({id:sampleId,path,hash:contentHash,rulesHash,jobId:job,runId:run,candidateId:candidate,itemId:chosen.itemId,note:note.trim(),createdAt:new Date().toISOString(),model:execution.plan.backend?.model??execution.plan.execution.model,backend:execution.plan.backend?.id??null});
81
+ return record;
82
+ });}catch(error){if(created)rmSync(created,{force:true});throw error;}
83
+ }
84
+
85
+ export async function removeStyleSample(settings,projectId,styleId,revision,sampleId){
86
+ return mutateObject(settings,projectId,'style',styleId,revision,record=>{
87
+ const selected=(record.samples??[]).find(sample=>sample.id===sampleId);
88
+ if(!selected)throw new Error('运行时参考不存在');
89
+ // Keep bytes for historical plans and running batches; removal changes future selection only.
90
+ record.samples=record.samples.filter(sample=>sample.id!==sampleId&&(!selected.hash||sample.hash!==selected.hash));return record;
91
+ });
92
+ }