@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
@@ -1,120 +1,125 @@
1
- import {join} from 'node:path';
2
- import {randomUUID} from 'node:crypto';
3
- import {existsSync,openSync,closeSync,rmSync,cpSync,mkdirSync} from 'node:fs';
4
- import {spawn} from 'node:child_process';
5
- import {fileURLToPath} from 'node:url';
6
- import {readObject,verifyReferences,ownedPath,objectFile,objectDirectory} from './workspace.mjs';
7
- import {runtimeRoot,tasks,locked,taskFile,alive,stateRead} from './runtime.mjs';
8
- import {taskStatus,taskView} from './tasks.mjs';
9
- import {assertIdle} from './lifecycle.mjs';
10
- import {writeJson,readJson,hash} from './shared.mjs';
11
- import {analyzeStyle} from './analyze.mjs';
12
- import {referenceInput,analyzeTaskReferences} from './task-references.mjs';
13
- import {freezeCore,validateReport} from './core.mjs';
14
- import {styleReviewState,issueFingerprint,validateIssues,resolvedRecommendation,validateStyleConfig,styleSourceHash,styleEvidenceHash} from './style-review.mjs';
15
- import {mutateObject} from './workspace.mjs';
16
- import {REFERENCE_CATEGORIES} from './style-contract.mjs';
17
-
18
- export function analysisInput(settings,record){
19
- const scopes=Object.fromEntries(REFERENCE_CATEGORIES.map(c=>[c.directory,c.scope]));
20
- 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??''};})};
21
- }
22
-
23
- /** User-authored rules reuse unchanged evidence; this is not a model analysis. */
24
- export async function reviseStyleRules(settings,projectId,styleId,revision,{rules,summary,note}={}){
25
- return mutateObject(settings,projectId,'style',styleId,revision,record=>{
26
- validateStyleConfig({rules});
27
- if(typeof summary!=='string'||!summary.trim()||summary.length>300)throw new Error('风格概述须为1至300字');
28
- if(typeof note!=='string'||!note.trim()||note.length>2000)throw new Error('请记录本次规则修改的用户依据');
29
- const prior=record.report;
30
- if(!prior)throw new Error('缺少可沿用的参考证据,请先分析');
31
- validateReport(prior.data,projectId);verifyReferences(settings.paths.workspace,record);
32
- if(prior.evidenceHash?prior.evidenceHash!==styleEvidenceHash(record):prior.sourceHash!==styleSourceHash(record))throw new Error('参考证据已变化,请重新分析;不能只修改规则沿用旧证据');
33
- if(!styleReviewState({...record,report:{...prior,sourceHash:styleSourceHash(record)}}).ready)throw new Error('仍有未确认的取舍,请先处理当前问题');
34
- 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;
35
- record.reviewHistory??=[];
36
- record.reviewHistory.push({type:'rules-revision',revision:record.revision+1,note:note.trim(),previousReport:structuredClone(prior)});
37
- record.config={...record.config,rules:structuredClone(rules)};
38
- const data={...structuredClone(prior.data),id:styleId,summary:summary.trim(),recommendation:{rules:structuredClone(rules)},issues:[],decisions:[],provenance:{method:'user-rules',sourceReportHash:hash(prior.data),evidence:prior.data.provenance?.evidence??prior.data.provenance??null,note:note.trim()}};
39
- validateReport(data,projectId);
40
- record.report={data,sourceRevision:record.revision+1,sourceHash:styleSourceHash(record),evidenceHash:styleEvidenceHash(record),path:null,runId:null};
41
- return record;
42
- });
43
- }
44
- export async function startAnalysis(settings,projectId,styleId,revision,{dry=false,kind='style',operationId=null}={}){
45
- const root=runtimeRoot(settings);
46
- const prepare=async()=>{
47
- 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));}}
48
- const record=readObject(settings.paths.workspace,projectId,kind,styleId);
49
- if(record.revision!==revision)throw new Error('风格版本冲突');if(record.status!=='draft')throw new Error('只有可编辑对象可分析');
50
- 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});
51
- if(dry)return preview;
52
- 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)),'风格');
53
- const gate=stateRead(join(root,'shutdown.json'));if(gate&&alive(gate.pid))throw new Error('服务正在关闭,不能启动分析');
54
- const taskId='task-'+randomUUID(),file=taskFile(root,taskId),logPath=join(root,'tasks',taskId+'.log');
55
- const evidence=ownedPath(objectDirectory(settings.paths.workspace,projectId,kind,styleId),'reports',taskId,'refs');
56
- 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;}
57
- 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);
58
- 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);
59
- 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;}
60
- child.unref();return {taskId,status:'queued',styleId,sourceRevision:revision};
61
- };
62
- return dry?prepare():locked(root,'control',prepare);
63
- }
64
- export async function adoptStyle(settings,projectId,styleId,revision,{note}={}){
65
- return locked(runtimeRoot(settings),'control',async()=>{
66
- const record=readObject(settings.paths.workspace,projectId,'style',styleId);
67
- if(record.status!=='draft'||record.revision!==revision)throw new Error('风格状态或版本已变化');
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.status='frozen';record.coreHash=core.coreHash;record.revision++;record.updatedAt=new Date().toISOString();
76
- try{writeJson(objectFile(settings.paths.workspace,projectId,'style',styleId),record);}catch(error){throw new Error('核心已冻结,但风格状态提交失败,需要恢复:'+error.message);}
77
- rmSync(journal,{force:true});return record;
78
- });
79
- }
80
-
81
-
82
- /** Complete an already authorized adoption after a crash; never create a second core. */
83
- export async function recoverStyleAdoption(settings,projectId,styleId){
84
- return locked(runtimeRoot(settings),'control',async()=>{
85
- const directory=objectDirectory(settings.paths.workspace,projectId,'style',styleId),journal=ownedPath(directory,'adoption.json');
86
- if(!existsSync(journal))return readObject(settings.paths.workspace,projectId,'style',styleId);
87
- const intent=readJson(journal);if(intent.project!==projectId||intent.styleId!==styleId)throw new Error('恢复事务身份不匹配');
88
- const file=objectFile(settings.paths.workspace,projectId,'style',styleId),record=readJson(file);
89
- if(record.revision!==intent.revision&&!(record.revision===intent.revision+1&&record.status==='frozen'))throw new Error('风格版本与恢复事务冲突');
90
- const corePath=ownedPath(directory,'core.json');
91
- 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('已有核心与恢复事务不匹配');}
92
- else core=freezeCore({projectId,report:intent.report,root:settings.paths.workspace,note:intent.note,history:intent.record.reviewHistory??[]});
93
- const projectFile=ownedPath(settings.paths.workspace,'projects',projectId,'project.json'),project=readJson(projectFile);
94
- if(!project.cores.includes(styleId)){project.cores.push(styleId);project.defaultCore??=styleId;project.revision++;writeJson(projectFile,project);}
95
- 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;
96
- });
97
- }
98
-
99
- /** Explicit decisions update the review, never rewrite reference evidence or raw model output. */
100
- export async function resolveStyleIssue(settings,projectId,styleId,revision,{issueId,optionId,note}={}){
101
- return mutateObject(settings,projectId,'style',styleId,revision,record=>{
102
- const state=styleReviewState(record);
103
- if(state.stale||!record.report)throw new Error(state.reason);
104
- validateReport(record.report.data,projectId);
105
- const report=record.report.data,issue=report.issues.find(i=>i.id===issueId);
106
- const option=issue?.options.find(o=>o.id===optionId);
107
- if(!issue||!option)throw new Error('问题或选项不存在,请重新读取');
108
- if(typeof note!=='string'||!note.trim()||note.length>2000)throw new Error('必须记录用户取舍依据');
109
- const touched=new Set([...option.remove,...option.upsert.map(r=>r.id)]);
110
- report.decisions=report.decisions.filter(d=>{
111
- if(d.issueId===issueId)return false;
112
- const old=report.issues.find(i=>i.id===d.issueId)?.options.find(o=>o.id===d.optionId);
113
- return old&&![...old.remove,...old.upsert.map(r=>r.id)].some(id=>touched.has(id));
114
- });
115
- report.decisions.push({issueId,fingerprint:issueFingerprint(issue),optionId,note:note.trim(),decidedAt:new Date().toISOString()});
116
- validateIssues(report);resolvedRecommendation(report);
117
- record.reviewHistory??=[];record.reviewHistory.push({revision:record.revision+1,runId:record.report.runId,decision:report.decisions.at(-1)});
118
- return record;
119
- });
120
- }
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
+ }
@@ -0,0 +1,201 @@
1
+ import { hash, keys, id, text, texts, choice } from "./shared.mjs";
2
+ import { ContractError, AnalysisError } from "./errors.mjs";
3
+ import {
4
+ STYLE_SCHEMA_VERSION,
5
+ OBSERVATION_SCOPES,
6
+ validateStyleConfig as validateCoreConfig,
7
+ } from "./style-contract.mjs";
8
+ const validateStyleConfig = validateCoreConfig;
9
+ export function validateReport(report, projectId) {
10
+ keys(
11
+ report,
12
+ [
13
+ "schema",
14
+ "schemaVersion",
15
+ "project",
16
+ "id",
17
+ "summary",
18
+ "observations",
19
+ "recommendation",
20
+ "issues",
21
+ "notes",
22
+ "decisions",
23
+ "provenance",
24
+ ],
25
+ "report",
26
+ );
27
+ if (report.schemaVersion !== STYLE_SCHEMA_VERSION)
28
+ throw new ContractError(
29
+ "风格报告职责版本已变化,请重新分析,不能采用旧报告",
30
+ );
31
+ if (
32
+ report.schema !== "art-workshop/style-report" ||
33
+ report.project !== projectId
34
+ )
35
+ throw new ContractError("风格报告身份不匹配");
36
+ id(report.id, "report.id");
37
+ text(report.summary, "report.summary", 300);
38
+ if (!Array.isArray(report.observations))
39
+ throw new ContractError("observations 必须为数组");
40
+ for (const item of report.observations) {
41
+ keys(
42
+ item,
43
+ ["source", "scope", "feature", "evidence", "confidence"],
44
+ "observation",
45
+ );
46
+ text(item.source, "source", 1024);
47
+ choice(item.scope, OBSERVATION_SCOPES, "scope");
48
+ text(item.feature, "feature");
49
+ text(item.evidence, "evidence");
50
+ if (
51
+ !Number.isFinite(item.confidence) ||
52
+ item.confidence < 0 ||
53
+ item.confidence > 1
54
+ )
55
+ throw new ContractError("confidence 必须在 0~1");
56
+ }
57
+ texts(report.notes, "notes", { empty: true });
58
+ validateIssues(report);
59
+ validateCoreConfig(report.recommendation);
60
+ return report;
61
+ }
62
+
63
+ export const issueFingerprint = (issue) =>
64
+ hash({ id: issue.id, question: issue.question, options: issue.options });
65
+ export function validateIssues(report) {
66
+ if (!Array.isArray(report.issues) || report.issues.length > 30)
67
+ throw new ContractError("问题列表非法");
68
+ const ids = new Set();
69
+ for (const issue of report.issues) {
70
+ keys(issue, ["id", "question", "options", "reopenReason"], "issue");
71
+ id(issue.id, "issue.id");
72
+ if (ids.has(issue.id)) throw new ContractError("问题ID重复");
73
+ ids.add(issue.id);
74
+ text(issue.question, "issue.question", 2000);
75
+ if (typeof issue.reopenReason !== "string")
76
+ throw new ContractError("问题重新打开原因必须是文本");
77
+ if (
78
+ !Array.isArray(issue.options) ||
79
+ issue.options.length < 2 ||
80
+ issue.options.length > 5
81
+ )
82
+ throw new ContractError("每个问题需要2至5个具体可执行方案");
83
+ const options = new Set();
84
+ for (const option of issue.options) {
85
+ keys(option, ["id", "label", "remove", "upsert"], "issue option");
86
+ id(option.id, "option.id");
87
+ if (options.has(option.id)) throw new ContractError("方案ID重复");
88
+ options.add(option.id);
89
+ text(option.label, "option.label", 1000);
90
+ texts(option.remove, "option.remove", { empty: true });
91
+ if (new Set(option.remove).size !== option.remove.length)
92
+ throw new ContractError("删除规则重复");
93
+ if (!Array.isArray(option.upsert))
94
+ throw new ContractError("方案规则非法");
95
+ if (option.upsert.length) validateStyleConfig({ rules: option.upsert });
96
+ applyOption(report.recommendation, option);
97
+ }
98
+ }
99
+ if (!Array.isArray(report.decisions))
100
+ throw new ContractError("问题决定必须是数组");
101
+ const decisions = new Set();
102
+ for (const decision of report.decisions) {
103
+ keys(
104
+ decision,
105
+ ["issueId", "fingerprint", "optionId", "note", "decidedAt"],
106
+ "decision",
107
+ );
108
+ const issue = report.issues.find((i) => i.id === decision.issueId);
109
+ if (
110
+ !issue ||
111
+ issueFingerprint(issue) !== decision.fingerprint ||
112
+ !issue.options.some((o) => o.id === decision.optionId) ||
113
+ decisions.has(issue.id)
114
+ )
115
+ throw new ContractError("问题决定与当前问题不匹配");
116
+ decisions.add(issue.id);
117
+ text(decision.note, "decision.note", 2000);
118
+ text(decision.decidedAt, "decision.decidedAt");
119
+ }
120
+ }
121
+ export function applyOption(config, option) {
122
+ const rules = config.rules.filter((r) => !option.remove.includes(r.id));
123
+ for (const rule of option.upsert) {
124
+ const index = rules.findIndex((r) => r.id === rule.id);
125
+ if (index < 0) rules.push(rule);
126
+ else rules[index] = rule;
127
+ }
128
+ return validateStyleConfig({ rules });
129
+ }
130
+ export function unresolvedIssues(report) {
131
+ return report.issues.filter(
132
+ (issue) =>
133
+ !report.decisions.some(
134
+ (d) =>
135
+ d.issueId === issue.id && d.fingerprint === issueFingerprint(issue),
136
+ ),
137
+ );
138
+ }
139
+ export function resolvedRecommendation(report) {
140
+ return report.decisions.reduce((config, decision) => {
141
+ const issue = report.issues.find((i) => i.id === decision.issueId);
142
+ if (!issue || issueFingerprint(issue) !== decision.fingerprint)
143
+ throw new ContractError("已确认问题发生变化,请重新决定");
144
+ return applyOption(
145
+ config,
146
+ issue.options.find((o) => o.id === decision.optionId),
147
+ );
148
+ }, report.recommendation);
149
+ }
150
+
151
+ export function assertReportIdentity(report, expected) {
152
+ if (report.project !== expected.project || report.id !== expected.id)
153
+ throw new AnalysisError(
154
+ "REPORT_IDENTITY_MISMATCH",
155
+ "风格报告身份与当前对象不匹配",
156
+ { recovery: "review-report" },
157
+ );
158
+ }
159
+ export function inspectStyleReport(report, expected) {
160
+ try {
161
+ validateReport(report, expected.project);
162
+ assertReportIdentity(report, expected);
163
+ return { valid: true };
164
+ } catch (error) {
165
+ return {
166
+ valid: false,
167
+ reason: error.message,
168
+ code: error.code ?? "REPORT_FORMAT_INVALID",
169
+ };
170
+ }
171
+ }
172
+ export function modelStyleReport(value, expected, provenance) {
173
+ if (!value) throw new ContractError("模型未返回有效风格报告 JSON");
174
+ for (const [key, want] of Object.entries({
175
+ schema: "art-workshop/style-report",
176
+ schemaVersion: STYLE_SCHEMA_VERSION,
177
+ project: expected.project,
178
+ id: expected.id,
179
+ }))
180
+ if (value[key] !== undefined && value[key] !== want)
181
+ throw new AnalysisError(
182
+ "REPORT_IDENTITY_MISMATCH",
183
+ "风格报告身份或职责版本与当前对象不匹配",
184
+ { recovery: "review-report" },
185
+ );
186
+ if (value.decisions?.length)
187
+ throw new AnalysisError(
188
+ "REPORT_FORGED_DECISION",
189
+ "模型不能代替用户确认风格取舍",
190
+ );
191
+ const report = {
192
+ ...value,
193
+ schema: "art-workshop/style-report",
194
+ schemaVersion: STYLE_SCHEMA_VERSION,
195
+ ...expected,
196
+ provenance,
197
+ decisions: [],
198
+ };
199
+ validateReport(report, expected.project);
200
+ return report;
201
+ }
@@ -1,75 +1,14 @@
1
- import {hash,keys,id,text,choice,texts} from './shared.mjs';
2
- import {RULE_SCOPES,RULE_STRENGTHS,STYLE_SCHEMA_VERSION} from './style-contract.mjs';
3
-
4
- export function validateStyleConfig(config){
5
- keys(config,['rules'],'style rules');
6
- if(!Array.isArray(config.rules)||!config.rules.length||config.rules.length>60)throw new Error('风格必须包含1至60条规则');
7
- const ids=new Set();
8
- for(const rule of config.rules){
9
- keys(rule,['id','scope','strength','instruction','when','negative'],'style rule');
10
- id(rule.id,'rule.id');if(ids.has(rule.id))throw new Error('规则ID重复');ids.add(rule.id);
11
- choice(rule.scope,RULE_SCOPES,'rule.scope');choice(rule.strength,RULE_STRENGTHS,'rule.strength');
12
- text(rule.instruction,'rule.instruction',300);
13
- if(/本轮|上一[轮版]|上次|本次调整|已[经]?修改|为解决.*冲突/.test(rule.instruction))throw new Error('风格规则必须为独立成稿,不包含迭代过程描述');
14
- if(typeof rule.when!=='string'||rule.when.length>1000)throw new Error('规则适用条件非法');
15
- if(rule.negative!==undefined){
16
- if(rule.strength!=='avoid')throw new Error('仅 avoid 规则可配置 negative;默认倾向不能升级为负向禁止');
17
- if(!Array.isArray(rule.negative)||rule.negative.length>20)throw new Error('规则 negative 必须为不超过20项的字符串数组');
18
- for(const term of rule.negative){
19
- text(term,'rule.negative',200);
20
- if(/^(?:避免|不要|不得|禁止|不允许|不使用|排除|no\b|without\b|avoid\b)/i.test(term.trim()))throw new Error('negative 直接描述被排除的绘制特征,不加否定前缀;适用条件写入 when');
21
- }
22
- }
23
- }
24
- return config;
25
- }
26
- export const issueFingerprint=issue=>hash({id:issue.id,question:issue.question,options:issue.options});
27
- export function validateIssues(report){
28
- if(!Array.isArray(report.issues)||report.issues.length>30)throw new Error('问题列表非法');
29
- const ids=new Set();
30
- for(const issue of report.issues){
31
- keys(issue,['id','question','options','reopenReason'],'issue');id(issue.id,'issue.id');
32
- if(ids.has(issue.id))throw new Error('问题ID重复');ids.add(issue.id);text(issue.question,'issue.question',2000);
33
- if(typeof issue.reopenReason!=='string')throw new Error('问题重新打开原因必须是文本');
34
- if(!Array.isArray(issue.options)||issue.options.length<2||issue.options.length>5)throw new Error('每个问题需要2至5个具体可执行方案');
35
- const options=new Set();
36
- for(const option of issue.options){
37
- keys(option,['id','label','remove','upsert'],'issue option');id(option.id,'option.id');
38
- if(options.has(option.id))throw new Error('方案ID重复');options.add(option.id);text(option.label,'option.label',1000);
39
- texts(option.remove,'option.remove',{empty:true});if(new Set(option.remove).size!==option.remove.length)throw new Error('删除规则重复');
40
- if(!Array.isArray(option.upsert))throw new Error('方案规则非法');
41
- if(option.upsert.length)validateStyleConfig({rules:option.upsert});
42
- applyOption(report.recommendation,option);
43
- }
44
- }
45
- if(!Array.isArray(report.decisions))throw new Error('问题决定必须是数组');
46
- const decisions=new Set();
47
- for(const decision of report.decisions){
48
- keys(decision,['issueId','fingerprint','optionId','note','decidedAt'],'decision');
49
- const issue=report.issues.find(i=>i.id===decision.issueId);
50
- if(!issue||issueFingerprint(issue)!==decision.fingerprint||!issue.options.some(o=>o.id===decision.optionId)||decisions.has(issue.id))throw new Error('问题决定与当前问题不匹配');
51
- decisions.add(issue.id);text(decision.note,'decision.note',2000);text(decision.decidedAt,'decision.decidedAt');
52
- }
53
- }
54
- export function applyOption(config,option){
55
- const rules=config.rules.filter(r=>!option.remove.includes(r.id));
56
- for(const rule of option.upsert){const index=rules.findIndex(r=>r.id===rule.id);if(index<0)rules.push(rule);else rules[index]=rule;}
57
- return validateStyleConfig({rules});
58
- }
59
- export function unresolvedIssues(report){return report.issues.filter(issue=>!report.decisions.some(d=>d.issueId===issue.id&&d.fingerprint===issueFingerprint(issue)));}
60
- export function styleSourceHash(record){return hash({config:record.config,references:record.references});}
61
- export function styleEvidenceHash(record){return hash({references:record.references,analysis:record.config.analysis??null});}
62
- export function styleReviewState(record){
63
- if(!record.report)return {ready:false,stale:false,openIssues:[],reason:'请先生成风格报告'};
64
- if(record.report.data.schemaVersion!==STYLE_SCHEMA_VERSION)return {ready:false,stale:true,openIssues:[],reason:'历史报告已保留,请生成新版风格报告'};
65
- const stale=record.report.sourceHash!==styleSourceHash(record),openIssues=unresolvedIssues(record.report.data).map(i=>i.id);
66
- return {ready:!stale&&!openIssues.length,stale,openIssues,recommendation:resolvedRecommendation(record.report.data),reason:stale?'草稿或参考已修改,请复核报告':openIssues.length?`还有 ${openIssues.length} 项待决定;确认取舍后即可采用`:'风格方案已就绪,可确认采用'};
67
- }
68
-
69
- export function resolvedRecommendation(report){
70
- return report.decisions.reduce((config,decision)=>{
71
- const issue=report.issues.find(i=>i.id===decision.issueId);
72
- if(!issue||issueFingerprint(issue)!==decision.fingerprint)throw new Error('已确认问题发生变化,请重新决定');
73
- return applyOption(config,issue.options.find(o=>o.id===decision.optionId));
74
- },report.recommendation);
75
- }
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
+ }