@kevlns/art-workshop 0.5.0 → 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 (42) hide show
  1. package/AGENTS.md +6 -90
  2. package/README.md +1 -1
  3. package/art-workshop.mjs +15 -9
  4. package/docs/commands.md +116 -8
  5. package/docs/configuration.md +1 -1
  6. package/lib/agent.mjs +19 -34
  7. package/lib/analysis-worker.mjs +5 -2
  8. package/lib/analyze.mjs +27 -20
  9. package/lib/asset-profile.mjs +2 -0
  10. package/lib/candidates.mjs +2 -0
  11. package/lib/conversation.mjs +77 -0
  12. package/lib/core.mjs +3 -17
  13. package/lib/edit.mjs +2 -1
  14. package/lib/errors.mjs +32 -0
  15. package/lib/generate.mjs +2 -1
  16. package/lib/object-format.mjs +112 -0
  17. package/lib/process-identity.mjs +17 -9
  18. package/lib/service.mjs +16 -8
  19. package/lib/settings.mjs +1 -1
  20. package/lib/shared.mjs +10 -9
  21. package/lib/style-contract.mjs +39 -0
  22. package/lib/style-evidence.mjs +39 -0
  23. package/lib/style-lifecycle.mjs +6 -1
  24. package/lib/style-report.mjs +201 -0
  25. package/lib/style-review.mjs +7 -68
  26. package/lib/task-contract.mjs +2 -0
  27. package/lib/tasks.mjs +2 -0
  28. package/lib/templates.mjs +7 -1
  29. package/lib/vision.mjs +16 -6
  30. package/lib/worker-process.mjs +6 -6
  31. package/lib/workspace.mjs +74 -20
  32. package/package.json +3 -5
  33. package/skills/art-workshop/SKILL.md +9 -108
  34. package/skills/art-workshop/references/conversation.md +11 -0
  35. package/skills/art-workshop/references/expression.md +27 -0
  36. package/skills/art-workshop/references/getty.md +76 -0
  37. package/skills/art-workshop/references/project.md +109 -0
  38. package/skills/art-workshop/references/style-discussion.md +27 -0
  39. package/skills/art-workshop/scripts/getty.py +269 -0
  40. package/v-cli.plugin.json +271 -15
  41. package/scripts/sync-skill.mjs +0 -6
  42. /package/{skills/art-workshop → adapters/codex}/agents/openai.yaml +0 -0
@@ -0,0 +1,77 @@
1
+ import {existsSync,readFileSync} from 'node:fs';
2
+ import {join,resolve,dirname,relative,isAbsolute} from 'node:path';
3
+ import {keys,id,description,integer,hash,readJson,writeJson} from './shared.mjs';
4
+ import {execution,finishPlan} from './plan.mjs';
5
+ import {backendDefaults,bindBackend} from './backends.mjs';
6
+ import {startTask,taskStatus,taskView,recoverTask,cancelTask,resumeTask,shutdown} from './tasks.mjs';
7
+ import {runtimeRoot,locked,tasks} from './runtime.mjs';
8
+ import {sha256File} from './bl.mjs';
9
+ import {externalPath} from './settings.mjs';
10
+ import {validateImage} from './images.mjs';
11
+
12
+ export function conversationFile(settings,session,request){id(session,'session');id(request,'request');return join(settings.paths.workspace,'conversations',session,request+'.json');}
13
+ export async function compileConversation(request,settings){
14
+ keys(request,['sessionId','requestId','mode','prompt','negative','images','preserve','style','size','count','seed','backend'],'conversation');
15
+ id(request.sessionId,'sessionId');id(request.requestId,'requestId');
16
+ if(!['generate','edit'].includes(request.mode))throw new Error('会话模式必须为 generate 或 edit');
17
+ description(request.prompt,'prompt');
18
+ const images=request.images??[];if(!Array.isArray(images))throw new Error('images 必须为数组');
19
+ if(request.mode==='edit'&&!images.length)throw new Error('编辑必须明确底图');
20
+ const refs=await Promise.all(images.map(async(image,index)=>{keys(image,['path','purpose'],'image');description(image.purpose,'purpose');const path=externalPath(resolve(image.path));await validateImage(readFileSync(path));return {path,hash:sha256File(path),purpose:image.purpose,index:index+1};}));
21
+ const selected=request.backend??settings.generation?.defaultBackend;
22
+ const config=execution({}, {...(request.size?{size:request.size}:{}),...(request.count!==undefined?{perValue:request.count}: {})},backendDefaults(settings,selected));
23
+ const seed=request.seed??parseInt(hash([request.sessionId,request.requestId]).slice(0,7),16);integer(seed,'seed');
24
+ const prompt=[request.prompt,request.style?'绘制语言:'+description(request.style,'style'):'',request.preserve?'必须保留:'+description(request.preserve,'preserve'):'',...refs.map(r=>'输入图'+r.index+'仅用于:'+r.purpose)].filter(Boolean).join('\n');
25
+ const plan=finishPlan({compilerVersion:4,module:refs.length?'edit':request.mode,scope:{kind:'conversation',sessionId:request.sessionId,requestId:request.requestId},project:'conversation-'+hash(request.sessionId).slice(0,32),job:request.requestId,execution:config,sources:{requestHash:hash(request)},snapshots:{request},refs:refs.map(({path,hash})=>({path,hash})),items:[{itemId:'image',variantId:'base',seed,prompt,negativeBlock:request.negative??'',imageArgs:refs.map(r=>r.path),checks:{content:[],style:[],asset:[]}}]});
26
+ return bindBackend(plan,settings,selected);
27
+ }
28
+
29
+ export async function startConversation(request,settings){
30
+ const file=conversationFile(settings,request.sessionId,request.requestId);
31
+ return locked(runtimeRoot(settings),'conversation',async()=>{
32
+ if(existsSync(file)){
33
+ const existing=readJson(file);if(hash(existing.request)!==hash(request))throw new Error('同一会话请求已提交,不能修改请求后重投');
34
+ return readConversationStatus(settings,request.sessionId,request.requestId);
35
+ }
36
+ const plan=await compileConversation(request,settings),operationId='conversation-'+hash([request.sessionId,request.requestId]).slice(0,48);
37
+ const record={schema:'art-workshop/conversation',request,plan,operationId,status:'dispatching',createdAt:new Date().toISOString()};
38
+ writeJson(file,record);
39
+ try{const started=await startTask(plan,plan.items,settings,{operationId});record.runId=started.taskId;record.status='queued';writeJson(file,record);}
40
+ catch(error){record.status='unknown';record.error=error.message;writeJson(file,record);}
41
+ return readConversationStatus(settings,request.sessionId,request.requestId);
42
+ },{timeout:10000});
43
+ }
44
+ export async function conversationStatus(settings,session,request){
45
+ return locked(runtimeRoot(settings),'conversation',()=>readConversationStatus(settings,session,request),{timeout:10000});
46
+ }
47
+ function readConversationStatus(settings,session,request){
48
+ const file=conversationFile(settings,session,request);
49
+ if(!existsSync(file))return {requestId:request,status:'failed',stopConfirmed:true,preSubmission:true,stopPolling:true,error:'未登记请求,未提交上游',artifacts:[]};
50
+ const record=readJson(file);
51
+ if(!record.runId){
52
+ try{const recovered=recoverTask(runtimeRoot(settings),record.plan.project,record.operationId);record.runId=recovered.taskId;writeJson(file,record);}catch{}
53
+ }
54
+ if(!record.runId){
55
+ // startTask 在拉起工作进程前持久登记;持有会话锁且无任务才可证明未提交。
56
+ const matches=tasks(runtimeRoot(settings)).filter(t=>t.operationId===record.operationId);
57
+ if(matches.length)throw new Error('原运行证据冲突,不能重投');
58
+ record.status='failed';writeJson(file,record);
59
+ return {requestId:request,status:'failed',stopConfirmed:true,preSubmission:true,stopPolling:true,error:record.error??'上游提交前已停止',artifacts:[]};
60
+ }
61
+ const task=taskStatus(runtimeRoot(settings),record.runId),view=taskView(task),artifacts=[];
62
+ if(task.manifestPath&&existsSync(task.manifestPath)){
63
+ const manifest=readJson(task.manifestPath);if(manifest.taskId!==task.taskId||manifest.planHash!==record.plan.planHash)throw new Error('会话产物身份不一致');
64
+ for(const row of manifest.items??[])if(row.ok)for(const name of row.files??[]){const path=resolve(dirname(task.manifestPath),name),delta=relative(dirname(task.manifestPath),path);if(isAbsolute(delta)||delta.startsWith('..'))throw new Error('会话图片路径越界');if(!row.outputHashes?.[name]||sha256File(path)!==row.outputHashes[name])throw new Error('会话图片已变化');artifacts.push({path,sha256:row.outputHashes[name]});}
65
+ }
66
+ return {requestId:request,runId:task.taskId,status:view.status,stopConfirmed:view.stopConfirmed,canResume:view.canResume,stopPolling:['succeeded','failed','cancelled','unknown'].includes(view.status),error:view.error,artifacts};
67
+ }
68
+ export async function controlConversation(settings,session,request,action){
69
+ return locked(runtimeRoot(settings),'conversation',async()=>{
70
+ if(action==='close')return shutdown(settings,{closeServices:false});
71
+ const current=readConversationStatus(settings,session,request);if(!current.runId)return current;
72
+ if(action==='cancel')await cancelTask(runtimeRoot(settings),current.runId,{wait:false});
73
+ else if(action==='resume')await resumeTask(runtimeRoot(settings),current.runId);
74
+ else throw new Error('未知会话控制动作');
75
+ return readConversationStatus(settings,session,request);
76
+ },{timeout:10000});
77
+ }
package/lib/core.mjs CHANGED
@@ -8,25 +8,11 @@ export {EXAMPLE_CONFIG} from './style-contract.mjs';
8
8
 
9
9
  export function guidance() { return readJson(join(TOOL_ROOT, 'rules', 'core-guidance.json')); }
10
10
 
11
- export {validateStyleConfig as validateCoreConfig} from './style-review.mjs';
11
+ export {validateStyleConfig as validateCoreConfig} from './style-contract.mjs';
12
+ export {validateReport} from './style-report.mjs';
13
+ import {validateReport} from './style-report.mjs';
12
14
  import {validateStyleConfig as validateCoreConfig,validateIssues,unresolvedIssues,resolvedRecommendation} from './style-review.mjs';
13
15
 
14
- export function validateReport(report, projectId) {
15
- keys(report, ['schema', 'schemaVersion', 'project', 'id', 'summary', 'observations', 'recommendation', 'issues', 'notes', 'decisions', 'provenance'], 'report');
16
- if(report.schemaVersion!==STYLE_SCHEMA_VERSION)throw new Error('风格报告职责版本已变化,请重新分析,不能采用旧报告');
17
- if (report.schema !== 'art-workshop/style-report' || report.project !== projectId) throw new Error('风格报告身份不匹配');
18
- id(report.id, 'report.id'); text(report.summary, 'report.summary', 300);
19
- if (!Array.isArray(report.observations)) throw new Error('observations 必须为数组');
20
- for (const item of report.observations) {
21
- keys(item, ['source', 'scope', 'feature', 'evidence', 'confidence'], 'observation');
22
- text(item.source, 'source', 1024); choice(item.scope, OBSERVATION_SCOPES, 'scope');
23
- text(item.feature, 'feature'); text(item.evidence, 'evidence');
24
- if (!Number.isFinite(item.confidence) || item.confidence < 0 || item.confidence > 1) throw new Error('confidence 必须在 0~1');
25
- }
26
- texts(report.notes, 'notes', { empty: true }); validateIssues(report);
27
- validateCoreConfig(report.recommendation); return report;
28
- }
29
-
30
16
  export function freezeCore({ projectId, report, root = ROOT, note = '确认采用此报告推荐配置', history=[] }) {
31
17
  const project = loadProject(projectId, root); validateReport(report, projectId);
32
18
  if (unresolvedIssues(report).length) throw new Error('仍有待决定的问题;记录取舍后再采用');
package/lib/edit.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import {assertObjectCurrent} from './workspace.mjs';
1
2
  import {EDIT_FIELDS,textSpecs,textSpecLine,textFidelityNegative} from './task-contract.mjs';
2
3
  import {description,descriptions} from './shared.mjs';
3
4
  import {editingPrompt,COMPILER_VERSION} from './prompt-structure.mjs';
@@ -11,7 +12,7 @@ import {execution,finishPlan} from './plan.mjs';
11
12
  import {background} from './presentation.mjs';
12
13
  import {sha256File} from './bl.mjs';
13
14
  export function compileEdit({projectId,jobId,coreId,root=ROOT,localExecution={}}) {
14
- const taskRecord=readObject(root,projectId,'task',jobId);const dynamicRefs=verifyReferences(root,taskRecord);
15
+ const taskRecord=readObject(root,projectId,'task',jobId);assertObjectCurrent(root,taskRecord);const dynamicRefs=verifyReferences(root,taskRecord);
15
16
  const project=loadProject(projectId,root),job=loadJob(projectId,jobId,'edit',root);
16
17
  keys(job,['project','kind','core','execution','analysis','generation','items'],'edit job');
17
18
  if(job.generation&&localExecution.model)job.execution={...job.execution,model:localExecution.model};
package/lib/errors.mjs ADDED
@@ -0,0 +1,32 @@
1
+ /** Expected contract failures are distinct from transport and programming errors. */
2
+ export class ContractError extends Error {
3
+ constructor(message, { code = "INPUT_INVALID", fieldPath } = {}) {
4
+ super(message);
5
+ this.name = "ContractError";
6
+ this.code = code;
7
+ this.fieldPath = fieldPath;
8
+ }
9
+ }
10
+ export class AnalysisError extends Error {
11
+ constructor(code, message, detail = {}) {
12
+ super(message);
13
+ this.name = "AnalysisError";
14
+ this.code = code;
15
+ Object.assign(this, detail);
16
+ }
17
+ }
18
+ export function errorDetail(error, stage) {
19
+ return {
20
+ code: error.code ?? "INTERNAL_ERROR",
21
+ stage,
22
+ message: error.message ?? String(error),
23
+ ...(error.fieldPath ? { fieldPath: error.fieldPath } : {}),
24
+ ...(error.upstream ? { upstream: error.upstream } : {}),
25
+ ...(error.effectiveMaxTokens
26
+ ? { effectiveMaxTokens: error.effectiveMaxTokens }
27
+ : {}),
28
+ recovery:
29
+ error.recovery ??
30
+ (error instanceof ContractError ? "fix-input" : "check-original-run"),
31
+ };
32
+ }
package/lib/generate.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import {assertObjectCurrent} from './workspace.mjs';
1
2
  import {description,descriptions} from './shared.mjs';
2
3
  import {generationPrompt,COMPILER_VERSION} from './prompt-structure.mjs';
3
4
  import {TRANSPARENT_OUTPUT} from './transparent-output.mjs';
@@ -12,7 +13,7 @@ import {presentation,assetPrompt} from './presentation.mjs';
12
13
  import {resolveAssetProfile} from './asset-profile.mjs';
13
14
  import {design,designPrompt} from './design.mjs';
14
15
  export function compileGenerate({projectId,jobId,coreId,root=ROOT,localExecution={}}) {
15
- const taskRecord=readObject(root,projectId,'task',jobId);const dynamicRefs=verifyReferences(root,taskRecord);
16
+ const taskRecord=readObject(root,projectId,'task',jobId);assertObjectCurrent(root,taskRecord);const dynamicRefs=verifyReferences(root,taskRecord);
16
17
  const project=loadProject(projectId,root),job=loadJob(projectId,jobId,'generate',root);
17
18
  keys(job,['project','kind','core','profile','asset','execution','analysis','generation','items'],'job');
18
19
  if(job.generation&&localExecution.model)job.execution={...job.execution,model:localExecution.model};
@@ -0,0 +1,112 @@
1
+ import { keys } from "./shared.mjs";
2
+ import { STYLE_SCHEMA_VERSION, STYLE_CATEGORIES } from "./style-contract.mjs";
3
+ import {
4
+ GENERATION_FIELDS,
5
+ EDIT_FIELDS,
6
+ TASK_FIELDS,
7
+ } from "./task-contract.mjs";
8
+
9
+ /** Format recognition only. Missing content and absent optional fields are not deprecation. */
10
+ export function inspectObjectFormat(record, { core, dependency } = {}) {
11
+ const reasons = [];
12
+ if (
13
+ record.readError ||
14
+ (record.source?.kind === "migration" && !record.migration)
15
+ )
16
+ return {
17
+ status: "unreadable",
18
+ reasons: [record.readError ?? "迁移来源准备尚未完成,请从原对象重试派生"],
19
+ canEdit: false,
20
+ canDerive: false,
21
+ };
22
+ const kind = record.schema?.slice("art-workshop/".length);
23
+ if (
24
+ !record.config ||
25
+ typeof record.config !== "object" ||
26
+ Array.isArray(record.config)
27
+ )
28
+ return {
29
+ status: "unreadable",
30
+ reasons: ["配置数据无法读取"],
31
+ canEdit: false,
32
+ canDerive: false,
33
+ };
34
+ if (record.schemaVersion !== 2) reasons.push("对象格式已弃用");
35
+ try {
36
+ const c = record.config;
37
+ if (kind === "style") {
38
+ // Original frozen configs may use an earlier structured drawing contract.
39
+ keys(
40
+ c,
41
+ ["description", "constraints", "rules", "analysis"],
42
+ "style config",
43
+ );
44
+ if (c.rules !== undefined) {
45
+ if (!Array.isArray(c.rules)) throw Error("风格规则结构已弃用");
46
+ for (const rule of c.rules)
47
+ keys(
48
+ rule,
49
+ ["id", "scope", "strength", "instruction", "when", "negative"],
50
+ "style rule",
51
+ );
52
+ }
53
+ if (
54
+ record.report &&
55
+ record.report.data?.schemaVersion !== STYLE_SCHEMA_VERSION
56
+ )
57
+ reasons.push("风格报告职责格式已弃用");
58
+ if (
59
+ (record.references ?? []).some(
60
+ (r) => !STYLE_CATEGORIES.includes(r.category),
61
+ )
62
+ )
63
+ reasons.push("风格参考分类已弃用");
64
+ if (
65
+ record.status === "frozen" &&
66
+ (!core || core.schemaVersion !== STYLE_SCHEMA_VERSION)
67
+ )
68
+ reasons.push("冻结风格职责格式已弃用");
69
+ } else if (kind === "task") {
70
+ keys(c, TASK_FIELDS[c.kind] ?? [], "task config");
71
+ if (!["generate", "edit"].includes(c.kind))
72
+ reasons.push("任务类型格式已弃用");
73
+ for (const item of c.items ?? []) {
74
+ keys(
75
+ item,
76
+ c.kind === "edit" ? EDIT_FIELDS : GENERATION_FIELDS.item,
77
+ "item",
78
+ );
79
+ if (c.kind === "generate")
80
+ for (const [field, shape] of [
81
+ ["entities", "entity"],
82
+ ["effects", "effect"],
83
+ ["relations", "relation"],
84
+ ["variants", "variant"],
85
+ ])
86
+ for (const row of item[field] ?? [])
87
+ keys(row, GENERATION_FIELDS[shape], shape);
88
+ }
89
+ if (c.core && (!dependency || dependency.status !== "current"))
90
+ reasons.push("所用风格已弃用或不可用");
91
+ } else reasons.push("对象类型格式已弃用");
92
+ } catch (error) {
93
+ reasons.push(error.message);
94
+ }
95
+ const status = reasons.length ? "deprecated" : "current";
96
+ if (reasons.length) reasons[reasons.length - 1] += ",请派生迁移";
97
+ return {
98
+ status,
99
+ reasons,
100
+ canEdit: status === "current" && record.status !== "frozen",
101
+ canDerive: !["discarded", "cleanup-required"].includes(record.status),
102
+ };
103
+ }
104
+ export function assertSupportedObject(format) {
105
+ if (format.status !== "current")
106
+ throw Object.assign(
107
+ new Error(
108
+ "格式弃用:" + format.reasons.join(";") + "。请派生迁移为当前格式草稿",
109
+ ),
110
+ { code: "FORMAT_DEPRECATED" },
111
+ );
112
+ }
@@ -1,14 +1,22 @@
1
1
  import {execFileSync} from 'node:child_process';
2
- export function processIdentity(pid) {
3
- if(!Number.isSafeInteger(pid)||pid<1)return null;
2
+ export function inspectProcess(pid, run = execFileSync, timeout = 5000) {
3
+ if(!Number.isSafeInteger(pid)||pid<1)return {state:'missing'};
4
4
  try {
5
+ const options={encoding:'utf8',windowsHide:true,timeout,stdio:['ignore','pipe','pipe']};
5
6
  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;
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'};
9
12
  }
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;}
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
+ }
14
20
  }
21
+ // 启动时系统查询可能冷启动;登记身份仍有总上限,退出探测保持短等待。
22
+ export function processIdentity(pid) { return inspectProcess(pid, execFileSync, 15000).identity ?? null; }
package/lib/service.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import {processIdentity} from './process-identity.mjs';
1
+ import {processIdentity,inspectProcess} from './process-identity.mjs';
2
2
  export {processIdentity} from './process-identity.mjs';
3
3
  import {homedir} from 'node:os';
4
4
  import {spawn,execFileSync} from 'node:child_process';
@@ -9,14 +9,22 @@ import {writeJson,hash} from './shared.mjs';
9
9
  import {http,sleep,locked,stateRead,alive} from './runtime.mjs';
10
10
  import {inspectEnvironment,workflowError} from './diagnostics.mjs';
11
11
 
12
- export async function stopIdentity(identity,{timeout=10000}={}) {
13
- const current=processIdentity(identity.pid);
14
- if(!current)return;
15
- if(hash(current)!==hash(identity))throw new Error('服务进程身份已变化,拒绝终止复用的 PID');
16
- if(process.platform==='win32')execFileSync('taskkill.exe',['/PID',String(identity.pid),'/T','/F'],{windowsHide:true});
17
- else process.kill(identity.pid,'SIGTERM');
12
+ export async function stopIdentity(identity,{timeout=10000,inspect=inspectProcess}={}) {
13
+ const current=inspect(identity.pid);
14
+ if(current.state==='missing')return;
15
+ if(current.state!=='running')throw new Error('服务进程身份未知,无法确认停止');
16
+ if(hash(current.identity)!==hash(identity))throw new Error('服务进程身份已变化,拒绝终止复用的 PID');
17
+ try {
18
+ if(process.platform==='win32')execFileSync('taskkill.exe',['/PID',String(identity.pid),'/T','/F'],{windowsHide:true,timeout,stdio:['ignore','pipe','pipe']});
19
+ else process.kill(identity.pid,'SIGTERM');
20
+ }catch(error){if(inspect(identity.pid).state!=='missing')throw error;return;}
18
21
  const deadline=Date.now()+timeout;
19
- while(alive(identity.pid)){if(Date.now()>deadline)throw new Error('服务进程未停止');await sleep(100);}
22
+ while(true){
23
+ const result=inspect(identity.pid);
24
+ if(result.state==='missing'||result.state==='running'&&hash(result.identity)!==hash(identity))return;
25
+ if(result.state==='unknown')throw new Error('服务进程停止结果未知');
26
+ if(Date.now()>deadline)throw new Error('服务进程未停止');await sleep(100);
27
+ }
20
28
  }
21
29
  export async function healthy(endpoint,backend) {
22
30
  try {
package/lib/settings.mjs CHANGED
@@ -42,7 +42,7 @@ export function loadSettings({file=configFile(),workspace,output,refs,cache}={})
42
42
  if(local.autoSyncSkills!==undefined&&typeof local.autoSyncSkills!=='boolean')throw new Error('autoSyncSkills 必须为布尔值');
43
43
  const overrides={workspace,output,refs,cache},defaults={workspace:base,output:base,refs:join(base,'refs'),cache:join(base,'.cache')};
44
44
  const paths=Object.fromEntries(Object.keys(defaults).map(key=>[key,externalPath(overrides[key]??local.paths?.[key]??defaults[key],key)]));
45
- return {file:externalPath(file,'本地配置'),paths,execution:local.execution??{},generation:generationConfig(local.generation??{}),analysisModel:local.analysisModel??null,defaultProject:local.defaultProject??null,autoSyncSkills:local.autoSyncSkills??true};
45
+ return {file:externalPath(file,'本地配置'),paths,execution:local.execution??{},generation:generationConfig(local.generation??{}),analysisModel:local.analysisModel??null,defaultProject:local.defaultProject??null};
46
46
  }
47
47
  export function initSettings(file=configFile()) {
48
48
  externalPath(file,'本地配置');if(existsSync(file))return loadSettings({file});
package/lib/shared.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import {ContractError} from './errors.mjs';
1
2
  import { createHash, randomUUID } from 'node:crypto';
2
3
  import { readFileSync, writeFileSync, mkdirSync, renameSync, rmSync } from 'node:fs';
3
4
  import { dirname } from 'node:path';
@@ -31,33 +32,33 @@ export function writeJson(path, data) {
31
32
  } finally {try{rmSync(temporary,{force:true});}catch{}}
32
33
  }
33
34
  export function keys(value, allowed, label) {
34
- if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} 必须为对象`);
35
- for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new Error(`${label} 不支持字段 ${key}`);
35
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new ContractError(`${label} 必须为对象`);
36
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new ContractError(`${label} 不支持字段 ${key}`);
36
37
  }
37
38
  export function text(value, label, max = 160) {
38
- if (typeof value !== 'string' || !value.trim() || value.length > max) throw new Error(Number.isFinite(max) ? `${label} 必须是 1~${max} 字的精炼文本` : `${label} 必须是非空文本`);
39
- if (/\bTODO\b|<[^>]+>|待填写/.test(value)) throw new Error(`${label} 有未完成的占位符`);
39
+ if (typeof value !== 'string' || !value.trim() || value.length > max) throw new ContractError(Number.isFinite(max) ? `${label} 必须是 1~${max} 字的精炼文本` : `${label} 必须是非空文本`);
40
+ if (/\bTODO\b|<[^>]+>|待填写/.test(value)) throw new ContractError(`${label} 有未完成的占位符`);
40
41
  return value;
41
42
  }
42
43
  export function id(value, label = 'id') {
43
44
  if (typeof value !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(value)
44
- || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value)) throw new Error(`${label} 必须使用小写字母、数字、连字符`);
45
+ || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value)) throw new ContractError(`${label} 必须使用小写字母、数字、连字符`);
45
46
  return value;
46
47
  }
47
48
  export function integer(value, label, min = 0, max = 2147483647) {
48
- if (!Number.isSafeInteger(value) || value < min || value > max) throw new Error(`${label} 必须为 ${min}~${max} 的整数`);
49
+ if (!Number.isSafeInteger(value) || value < min || value > max) throw new ContractError(`${label} 必须为 ${min}~${max} 的整数`);
49
50
  return value;
50
51
  }
51
52
  export function choice(value, values, label) {
52
- if (!values.includes(value)) throw new Error(`${label} 必须为 ${values.join('/')}`);
53
+ if (!values.includes(value)) throw new ContractError(`${label} 必须为 ${values.join('/')}`);
53
54
  return value;
54
55
  }
55
56
  export function texts(value, label, { empty = false, max = 160 } = {}) {
56
- if (!Array.isArray(value) || (!empty && !value.length)) throw new Error(`${label} 必须为${empty ? '' : '非空'}数组`);
57
+ if (!Array.isArray(value) || (!empty && !value.length)) throw new ContractError(`${label} 必须为${empty ? '' : '非空'}数组`);
57
58
  value.forEach(x => text(x, label, max)); return value;
58
59
  }
59
60
  export function hex(value, label) {
60
- if (typeof value !== 'string' || !/^#[0-9a-f]{6}$/i.test(value)) throw new Error(`${label} 必须为 #RRGGBB`);
61
+ if (typeof value !== 'string' || !/^#[0-9a-f]{6}$/i.test(value)) throw new ContractError(`${label} 必须为 #RRGGBB`);
61
62
  return value.toUpperCase();
62
63
  }
63
64
 
@@ -1,3 +1,5 @@
1
+ import {hash,keys,id,text,texts,choice} from './shared.mjs';
2
+ import {ContractError} from './errors.mjs';
1
3
  /** Versioned drawing contract. Content and physical properties belong to each task. */
2
4
  export const STYLE_SCHEMA_VERSION=3;
3
5
  export const REFERENCE_CATEGORIES=[
@@ -33,3 +35,40 @@ export function assertExecutableStyle(plan){
33
35
  if(plan.sources?.core&&plan.snapshots?.core?.schemaVersion!==STYLE_SCHEMA_VERSION)
34
36
  throw new Error('旧风格计划需派生风格并重新分析采用、重新编译;历史证据仍可只读查看');
35
37
  }
38
+
39
+ export function validateStyleConfig(config){
40
+ keys(config,['rules'],'style rules');
41
+ if(!Array.isArray(config.rules)||!config.rules.length||config.rules.length>60)throw new ContractError('风格必须包含1至60条规则');
42
+ const ids=new Set();
43
+ for(const rule of config.rules){
44
+ keys(rule,['id','scope','strength','instruction','when','negative'],'style rule');
45
+ id(rule.id,'rule.id');if(ids.has(rule.id))throw new ContractError('规则ID重复');ids.add(rule.id);
46
+ choice(rule.scope,RULE_SCOPES,'rule.scope');choice(rule.strength,RULE_STRENGTHS,'rule.strength');
47
+ text(rule.instruction,'rule.instruction',300);
48
+ if(/本轮|上一[轮版]|上次|本次调整|已[经]?修改|为解决.*冲突/.test(rule.instruction))throw new ContractError('风格规则必须为独立成稿,不包含迭代过程描述');
49
+ if(typeof rule.when!=='string'||rule.when.length>1000)throw new ContractError('规则适用条件非法');
50
+ if(rule.negative!==undefined){
51
+ if(rule.strength!=='avoid')throw new ContractError('仅 avoid 规则可配置 negative;默认倾向不能升级为负向禁止');
52
+ if(!Array.isArray(rule.negative)||rule.negative.length>20)throw new ContractError('规则 negative 必须为不超过20项的字符串数组');
53
+ for(const term of rule.negative){
54
+ text(term,'rule.negative',200);
55
+ if(/^(?:避免|不要|不得|禁止|不允许|不使用|排除|no\b|without\b|avoid\b)/i.test(term.trim()))throw new ContractError('negative 直接描述被排除的绘制特征,不加否定前缀;适用条件写入 when');
56
+ }
57
+ }
58
+ }
59
+ return config;
60
+ }
61
+
62
+ export function validateStyleDraft(config){
63
+ keys(config,['description','constraints','rules','analysis'],'style config');
64
+ if(config.rules!==undefined)validateStyleConfig({rules:config.rules});
65
+ if(config.description!==undefined&&(typeof config.description!=='string'||config.description.length>12000))throw new ContractError('风格描述必须是12000字以内文本');
66
+ if(config.constraints!==undefined)texts(config.constraints,'constraints',{empty:true});
67
+ if(config.analysis!==undefined){keys(config.analysis,['provider','model'],'analysis');text(config.analysis.provider,'analysis.provider');text(config.analysis.model,'analysis.model');}
68
+ return structuredClone(config);
69
+ }
70
+
71
+ export const REFERENCE_NOTE_LIMIT=8000;
72
+ export function validateReferenceNotes({note='',ignore=''}={}){for(const [field,value] of Object.entries({note,ignore}))if(typeof value!=='string'||value.length>REFERENCE_NOTE_LIMIT)throw new ContractError('参考说明必须为8000字以内文本',{fieldPath:field});}
73
+ export function styleAnalysisReadiness(input){const config=input.config??input,refs=input.references??input.refs??[];const ready=!!(config.description?.trim()||config.constraints?.some(x=>x.trim())||config.rules?.length||refs.length);return {ready,reason:ready?'':'请补充风格说明、规则或参考图后分析'};}
74
+ export function styleContract(){return {schemaVersion:STYLE_SCHEMA_VERSION,fields:['description','constraints','rules','analysis'],referenceNoteLimit:REFERENCE_NOTE_LIMIT,analysisContent:'description、constraints、rules 或参考图至少有一项有效内容',rules:{scopes:RULE_SCOPES,strengths:RULE_STRENGTHS},migration:true};}
@@ -0,0 +1,39 @@
1
+ import { hash } from "./shared.mjs";
2
+ export function readStyleEvidence(provenance) {
3
+ const seen = new Set();
4
+ let value = provenance;
5
+ for (let depth = 0; depth < 32; depth++) {
6
+ if (!value || typeof value !== "object" || seen.has(value)) return null;
7
+ seen.add(value);
8
+ if (
9
+ Array.isArray(value.refs) &&
10
+ value.refs.every(
11
+ (r) => r && typeof r.hash === "string" && typeof r.scope === "string",
12
+ )
13
+ )
14
+ return value;
15
+ if (!["inherited-frozen", "user-rules"].includes(value.method)) return null;
16
+ value = value.evidence;
17
+ }
18
+ return null;
19
+ }
20
+ export const referenceEvidenceHash = (refs) =>
21
+ hash(
22
+ refs.map((r) => ({
23
+ hash: r.hash,
24
+ scope: r.scope,
25
+ note: r.note ?? "",
26
+ ignore: r.ignore ?? "",
27
+ })),
28
+ );
29
+ export function sameStyleEvidence(previous, refs) {
30
+ const evidence = readStyleEvidence(previous?.provenance);
31
+ return (
32
+ !!evidence &&
33
+ referenceEvidenceHash(evidence.refs) === referenceEvidenceHash(refs)
34
+ );
35
+ }
36
+ export function styleProvenance(previous, metadata) {
37
+ const evidence = readStyleEvidence(previous);
38
+ return { ...(evidence ? structuredClone(evidence) : {}), ...metadata };
39
+ }
@@ -1,3 +1,5 @@
1
+ import {assertObjectCurrent} from './workspace.mjs';
2
+ import {styleProvenance} from './style-evidence.mjs';
1
3
  import {join} from 'node:path';
2
4
  import {randomUUID} from 'node:crypto';
3
5
  import {existsSync,openSync,closeSync,rmSync,cpSync,mkdirSync} from 'node:fs';
@@ -35,7 +37,7 @@ export async function reviseStyleRules(settings,projectId,styleId,revision,{rule
35
37
  record.reviewHistory??=[];
36
38
  record.reviewHistory.push({type:'rules-revision',revision:record.revision+1,note:note.trim(),previousReport:structuredClone(prior)});
37
39
  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()}};
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()})};
39
41
  validateReport(data,projectId);
40
42
  record.report={data,sourceRevision:record.revision+1,sourceHash:styleSourceHash(record),evidenceHash:styleEvidenceHash(record),path:null,runId:null};
41
43
  return record;
@@ -46,6 +48,7 @@ export async function startAnalysis(settings,projectId,styleId,revision,{dry=fal
46
48
  const prepare=async()=>{
47
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));}}
48
50
  const record=readObject(settings.paths.workspace,projectId,kind,styleId);
51
+ assertObjectCurrent(settings.paths.workspace,record);
49
52
  if(record.revision!==revision)throw new Error('风格版本冲突');if(record.status!=='draft')throw new Error('只有可编辑对象可分析');
50
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});
51
54
  if(dry)return preview;
@@ -72,6 +75,7 @@ export async function adoptStyle(settings,projectId,styleId,revision,{note}={}){
72
75
  const journal=ownedPath(objectDirectory(settings.paths.workspace,projectId,'style',styleId),'adoption.json');
73
76
  writeJson(journal,{project:projectId,styleId,revision,report,note,record,createdAt:new Date().toISOString()});
74
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();
75
79
  record.status='frozen';record.coreHash=core.coreHash;record.revision++;record.updatedAt=new Date().toISOString();
76
80
  try{writeJson(objectFile(settings.paths.workspace,projectId,'style',styleId),record);}catch(error){throw new Error('核心已冻结,但风格状态提交失败,需要恢复:'+error.message);}
77
81
  rmSync(journal,{force:true});return record;
@@ -92,6 +96,7 @@ export async function recoverStyleAdoption(settings,projectId,styleId){
92
96
  else core=freezeCore({projectId,report:intent.report,root:settings.paths.workspace,note:intent.note,history:intent.record.reviewHistory??[]});
93
97
  const projectFile=ownedPath(settings.paths.workspace,'projects',projectId,'project.json'),project=readJson(projectFile);
94
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;
95
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;
96
101
  });
97
102
  }