292 lines
17 KiB
JavaScript
292 lines
17 KiB
JavaScript
import {projectTools} from '../src/project-tools.mjs';
|
||
import test from 'node:test';
|
||
import assert from 'node:assert/strict';
|
||
import fs from 'node:fs/promises';
|
||
import path from 'node:path';
|
||
import os from 'node:os';
|
||
import {createHash} from 'node:crypto';
|
||
import {DetailPiAgent} from '../src/agent.mjs';
|
||
import {EnterpriseContext} from '../src/enterprise-context.mjs';
|
||
import {openEnterpriseSkills} from '../src/enterprise-skill-resources.mjs';
|
||
import {EnterpriseKnowledge,enterpriseToolResult} from '../src/enterprise-knowledge.mjs';
|
||
|
||
test('selected resource guides are read completely with their own versions',async t=>{
|
||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-guides-'));
|
||
t.after(()=>fs.rm(root,{recursive:true}));
|
||
const calls=[],documents=[];
|
||
const display=['SKILL.md','SKILL.md','验图全文.md'];
|
||
const assets=display.map((name,index)=>({id:'guide-'+index,role:'guide',required:true,status:'available',
|
||
file:{name,path:'Skills/'+index+'/'+name,fileId:'file-'+index,revision:'revision-'+index}}));
|
||
assets.push({id:'optional',role:'guide',required:false,status:'available',
|
||
file:{name:'附录.md',path:'Skills/2/附录.md',fileId:'file-3',revision:'revision-3'}});
|
||
const client={
|
||
call:async(name,params)=>{
|
||
calls.push([name,params]);
|
||
if(name==='list_libraries')return {result:{navigation:[{name:'Skills',path:'Skills'}]}};
|
||
return {result:{revision:'view',resourceSet:{brand:'顾家',category:'电脑桌'},components:[{id:'visual_guides',status:'available',assets}]}};
|
||
},
|
||
readDocument:async (id,revision)=>{
|
||
documents.push([id,revision]);
|
||
return {result:{text:'第一页\n第二页',pages:2,revision}};
|
||
},
|
||
};
|
||
const ctx=new EnterpriseContext({root,appendEvent:async()=>{}},client);
|
||
const result=await ctx.load({task:'image',brandName:'顾家',categoryName:'电脑桌',resourceSetId:'selected'});
|
||
assert.deepEqual(calls.map(([name])=>name),['list_libraries','get_resource_set']);
|
||
assert.equal(calls[1][1].resourceSetId,'selected');
|
||
assert.deepEqual(documents,assets.slice(0,3).map(a=>[a.file.fileId,a.file.revision]));
|
||
assert.equal(result.skills.length,2);
|
||
assert.equal(result.rules[0].text,'第一页\n第二页');
|
||
assert.equal(result.rules[0].pages,2);
|
||
const production=await ctx.load({task:'production',brandName:'顾家',categoryName:'电脑桌',resourceSetId:'selected',outputId:'detail'});
|
||
assert.deepEqual(production.skills,result.skills);
|
||
assert.deepEqual(production.rules.map(rule=>rule.text),['第一页\n第二页','第一页\n第二页']);
|
||
assert.deepEqual(documents.slice(3),assets.map(a=>[a.file.fileId,a.file.revision]));
|
||
assert.deepEqual(calls.slice(2).map(([name])=>name),['list_libraries','get_resource_set']);
|
||
assets[0].file.revision='updated-after-first-load';
|
||
const current=await ctx.load({task:'production',brandName:'顾家',categoryName:'电脑桌',resourceSetId:'selected',outputId:'detail'});
|
||
assert.equal(current.skills[0].revision,'updated-after-first-load');
|
||
const attachment={name:'references.zip',path:'Skills/2/references.zip',fileId:'attachment',revision:'pinned'};
|
||
assets.push({id:'references',role:'attachment',status:'available',file:attachment});
|
||
const localPath=path.join(root,attachment.name);
|
||
await fs.writeFile(localPath,'fixture attachment');
|
||
client.download=async args=>{
|
||
assert.deepEqual(args,{fileId:'attachment',revision:'pinned'});
|
||
return {result:{localPath}};
|
||
};
|
||
const withAttachment=await ctx.load({task:'production',brandName:'顾家',categoryName:'电脑桌',resourceSetId:'selected'});
|
||
assert.equal(withAttachment.rules.at(-1).kind,'attachment');
|
||
assert.equal(Buffer.from(withAttachment.rules.at(-1).bytes,'base64').toString(),'fixture attachment');
|
||
});
|
||
|
||
test('a project downloads every declared guide at startup and reads only its locked local copy across rounds', async t => {
|
||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-template-guides-'));
|
||
t.after(()=>fs.rm(root,{recursive:true}));
|
||
const calls=[];
|
||
const docs=[];
|
||
const skillSources=[
|
||
{fileId:'workflow',path:'Skills/Lighting/SKILL.md',revision:'7'},
|
||
...Array.from({length:18},(_,index)=>({fileId:'rules-'+index,path:'Skills/Lighting/rule-'+index+'.md',revision:'11'})),
|
||
];
|
||
let liveRevision='11', status=200;
|
||
const client={
|
||
async call(name,args){
|
||
calls.push(name);
|
||
if(name==='list_libraries')return {result:{navigation:[{name:'Skills',path:'Skills'}]}};
|
||
if(name==='get_files')return {result:{results:args.files.map(ref=>({fileId:ref.fileId,
|
||
status:ref.fileId==='rules-0'?status:200}))}};
|
||
assert.equal(name,'get_resource_set');
|
||
return {result:{revision:liveRevision,resourceSet:{brand:'Lighting Lab',category:'灯具'},
|
||
components:[{id:'visual_guides',status:'available',assets:skillSources.map((file,index)=>({
|
||
id:file.fileId,role:'guide',required:index===0,status:'available',
|
||
file:{...file,name:path.basename(file.path),revision:index===1?liveRevision:file.revision},
|
||
}))}]}};
|
||
},
|
||
async readDocument(id,revision) {
|
||
docs.push([id,revision]);
|
||
return {result:{text:id==='workflow'
|
||
? '---\nname: lighting\ndescription: Lighting instructions.\n---\n[Review](rule-0.md)'
|
||
: 'rules body '+revision,revision}};
|
||
},
|
||
};
|
||
const store={root,dir:root,appendEvent:async()=>{}};
|
||
const ctx=new EnterpriseContext(store,client);
|
||
const input={task:'production',brandName:'Lighting Lab',categoryName:'灯具',resourceSetId:'light',releaseId:'release-3',skillSources:[]};
|
||
const binding=await openEnterpriseSkills(store,input,()=>ctx.load(input));
|
||
assert.deepEqual(calls,['list_libraries','get_resource_set']);
|
||
assert.deepEqual(docs,skillSources.map(({fileId,revision})=>[fileId,revision]));
|
||
assert.equal(binding.resource.skills[0].name,'lighting');
|
||
const {files}=binding;
|
||
assert.equal(files.length,19);
|
||
const reviewPath=files[1].path;
|
||
const {read}=await projectTools({store,productionSkills:binding});
|
||
const [result]=await Promise.all([
|
||
read('main').execute('',{path:reviewPath}),
|
||
binding.resolveFile(reviewPath),
|
||
]);
|
||
assert.equal(result.content[0].text,'rules body 11');
|
||
const reopen=()=>openEnterpriseSkills(store,{...input,releaseId:'release-4',outputId:'sku_images',runDeadline:500},
|
||
()=>assert.fail('use the existing project lock'),undefined,
|
||
pinned=>ctx.checkPinnedGuides(pinned,{read:execute=>execute()}));
|
||
assert.equal((await reopen()).versionNotice,undefined);
|
||
const offline=async()=>{ throw Object.assign(Error('网络离线'),{network:true}); };
|
||
const continued=await openEnterpriseSkills(store,input,()=>assert.fail('项目已有锁定资料'),undefined,offline);
|
||
assert.match(continued.versionNotice,/当前项目继续使用已锁定的版本:网络离线/u);
|
||
assert.equal(await fs.readFile(reviewPath,'utf8'),'rules body 11');
|
||
await assert.rejects(openEnterpriseSkills(store,{...input,resourceSetId:'new'},offline),/无法锁定最新企业知识:网络离线/u);
|
||
await assert.rejects(openEnterpriseSkills(store,input,()=>assert.fail('项目已有锁定资料'),undefined,
|
||
async()=>{throw new DOMException('项目已切换','AbortError');}),{name:'AbortError'});
|
||
liveRevision='12';
|
||
status=409;
|
||
assert.match((await reopen()).versionNotice,/有新版规则/u);
|
||
assert.equal(await fs.readFile(reviewPath,'utf8'),'rules body 11');
|
||
assert.equal(docs.length,19);
|
||
status=403;
|
||
await assert.rejects(reopen(),{status:403});
|
||
status=404;
|
||
assert.match((await reopen()).versionNotice,/当前项目继续使用已锁定的版本/u);
|
||
status=409;
|
||
await fs.writeFile(reviewPath,'corrupted');
|
||
await assert.rejects(reopen(),/本地副本校验失败/u);
|
||
});
|
||
|
||
test('the first bind pins metadata-only rules and leaves linked references on demand', async t => {
|
||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-declared-rules-'));
|
||
t.after(()=>fs.rm(root,{recursive:true}));
|
||
const sha256=text=>createHash('sha256').update(text).digest('hex');
|
||
const skill={fileId:'workflow',revision:'r1',path:'Skills/Lighting/SKILL.md',kind:'skill',
|
||
text:'---\nname: lighting\ndescription: Lighting instructions.\n---\n[附录](appendix.md)'};
|
||
const appendix={fileId:'appendix',revision:'r1',path:'Skills/Lighting/appendix.md'};
|
||
const bodies=Array.from({length:18},(_,index)=>`规则 ${index}\n${'灯'.repeat(4444)}`);
|
||
const rules=bodies.map((text,index)=>({fileId:'rule-'+index,revision:'r1',path:`Skills/Lighting/rule-${index}.md`,
|
||
kind:'guide',...(index===0?{sha256:sha256(text)}:{})}));
|
||
const knowledge={skills:[skill],rules,referenceSources:[appendix]};
|
||
const events=[], reads=[];
|
||
const store={root,dir:root,appendEvent:async event=>events.push(event)};
|
||
const selection={resourceSetId:'lighting',outputId:'detail'};
|
||
const loadReference=async (target,{source})=>{
|
||
assert.equal(source.path,target);
|
||
reads.push(source.fileId);
|
||
if(source.fileId===appendix.fileId)return {...source,kind:'native-reference',text:'按需读取的附录'};
|
||
const text=bodies[rules.indexOf(source)];
|
||
return {...source,text,sha256:sha256(text)};
|
||
};
|
||
const binding=await openEnterpriseSkills(store,selection,async()=>({...knowledge}),loadReference);
|
||
assert.deepEqual(reads,rules.map(({fileId})=>fileId));
|
||
const directory=path.join(root,'enterprise-skills',(await fs.readdir(path.join(root,'enterprise-skills')))[0]);
|
||
const snapshot=JSON.parse(await fs.readFile(path.join(directory,'snapshot.json'),'utf8'));
|
||
assert.deepEqual(snapshot.rules,rules.map((rule,index)=>({...rule,sha256:sha256(bodies[index])})));
|
||
assert.equal(snapshot.skills[0].sha256,sha256(skill.text));
|
||
for(const [index,rule] of rules.entries()) {
|
||
assert.equal(await fs.readFile(path.join(directory,'files',rule.path),'utf8'),bodies[index]);
|
||
}
|
||
const appendixPath=binding.files.find(({fileId})=>fileId===appendix.fileId).path;
|
||
await assert.rejects(fs.access(appendixPath),{code:'ENOENT'});
|
||
const {fileCount,bytes,elapsedMs}=events[0].download;
|
||
assert.equal(fileCount,19);
|
||
assert.equal(bytes,Buffer.byteLength(skill.text)+bodies.reduce((total,text)=>total+Buffer.byteLength(text),0));
|
||
t.diagnostic(`首次绑定离线耗时 ${elapsedMs} ms,${fileCount} 份,${bytes} 字节`);
|
||
|
||
const reopened=await openEnterpriseSkills(store,selection,()=>assert.fail('续做必须使用原锁定版本'),async target=>{
|
||
assert.equal(target,appendix.path);
|
||
return loadReference(target,{source:appendix});
|
||
},async()=>true);
|
||
assert.match(reopened.versionNotice,/有新版规则/u);
|
||
const {read}=await projectTools({store,productionSkills:reopened});
|
||
const result=await read('main').execute('',{path:reopened.files.find(({fileId})=>fileId===rules[0].fileId).path});
|
||
assert.equal(result.content[0].text,bodies[0]);
|
||
assert.equal(reads.length,rules.length);
|
||
assert.equal(await reopened.resolveFile(appendixPath),true);
|
||
assert.equal(reads.at(-1),appendix.fileId);
|
||
|
||
const wrongHash={...rules[0],sha256:sha256('另一版正文')};
|
||
await assert.rejects(openEnterpriseSkills(store,{...selection,resourceSetId:'bad-hash'},
|
||
async()=>({...knowledge,rules:[wrongHash]}),
|
||
async target=>loadReference(target,{source:rules[0]})),/rule-0\.md.*版本 r1/u);
|
||
assert.equal(events.filter(event=>event.download).length,1);
|
||
});
|
||
|
||
test('knowledge tools keep server rules, quota and policy in events and out of both model result channels', async () => {
|
||
const payload = {revision:'view',resourceSet:{resourceSetId:'selected'},components:[]};
|
||
const taskRules = {task:'production',required:true};
|
||
const usage={remaining:100}, policy={maxResponseCharacters:24000}, events=[];
|
||
const knowledge = new EnterpriseKnowledge({
|
||
store:{appendEvent:async event=>events.push(event)},
|
||
endpoints:['https://knowledge.test'],
|
||
fetchImpl:async (_url,options)=>{
|
||
if(!options.body) return Response.json({status:'ok',service:'enterprise-knowledge-base'});
|
||
const {id,method} = JSON.parse(options.body);
|
||
if(method!=='initialize') {
|
||
assert.equal(options.headers['Mcp-Session-Id'],'offline-session');
|
||
assert.equal(options.headers['MCP-Protocol-Version'],'2025-06-18');
|
||
}
|
||
if(method==='notifications/initialized') return new Response(null,{status:202});
|
||
const result={
|
||
initialize:{protocolVersion:'2025-06-18'},
|
||
'tools/list':{tools:[{name:'get_resource_set',inputSchema:{type:'object',
|
||
properties:{resourceSetId:{type:'string'},revision:{type:'string'}},
|
||
required:['resourceSetId'],additionalProperties:false}}]},
|
||
'tools/call':{content:[payload,{taskRules,usage,policy}].map(value=>({type:'text',text:JSON.stringify(value)}))},
|
||
}[method];
|
||
const envelope={jsonrpc:'2.0',id,result};
|
||
return new Response('event: message\ndata: '+JSON.stringify(envelope)+'\n\n',
|
||
{headers:{'content-type':'text/event-stream',...(method==='initialize'?{'mcp-session-id':'offline-session'}:{})}});
|
||
},
|
||
});
|
||
|
||
const reply=await knowledge.call('get_resource_set',{resourceSetId:'selected',revision:'view'});
|
||
const shown=enterpriseToolResult(reply);
|
||
assert.deepEqual(shown.details.result,payload);
|
||
assert.deepEqual(JSON.parse(shown.content[0].text).result,payload);
|
||
assert.deepEqual(events,[{type:'enterprise_knowledge_operational',tool:'get_resource_set',taskRules,usage,policy}]);
|
||
await assert.rejects(knowledge.call('get_resource_set',{resourceSetId:'selected',revision:'stale'}),{status:409});
|
||
});
|
||
|
||
test('a document with a mismatched normalized-text hash cannot be locked', async () => {
|
||
const knowledge=new EnterpriseKnowledge();
|
||
const text='版本锁定的正文';
|
||
const textSha256=createHash('sha256').update(text).digest('hex');
|
||
let body=text;
|
||
knowledge.call=async()=>({result:{revision:'one',text:body,textSha256,isLastPage:true,nextOffset:null}});
|
||
assert.equal((await knowledge.readDocument('guide','one')).result.text,text);
|
||
body+='另一个版本';
|
||
await assert.rejects(knowledge.readDocument('guide','one'),/全文校验失败/u);
|
||
});
|
||
|
||
|
||
test('制作锁定同时保存规则引用的图片、PDF 和 JSON 附件', async t => {
|
||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-guide-attachments-'));
|
||
t.after(()=>fs.rm(root,{recursive:true}));
|
||
const store={root,dir:root,appendEvent:async()=>{}};
|
||
const selection={resourceSetId:'attachments'};
|
||
const paths=['photo.png','spec.pdf','preset.json'];
|
||
const skill={fileId:'skill',revision:'1',path:'Skills/guide/SKILL.md',kind:'skill',
|
||
text:'---\nname: guide\ndescription: Guide.\n---\n'+paths.map(file=>'[资料]('+file+')').join('\n')};
|
||
const attached=await openEnterpriseSkills(store,selection,async()=>({skills:[skill],rules:[]}),async target=>({
|
||
fileId:path.posix.basename(target),revision:'1',path:target,kind:'attachment',bytes:Buffer.from(target).toString('base64'),
|
||
}));
|
||
const reopened=await openEnterpriseSkills(store,selection,()=>assert.fail('续做使用已经锁定的附件'));
|
||
for(const file of paths) {
|
||
const saved=reopened.files.find(entry=>entry.fileId===file);
|
||
assert.equal(await fs.readFile(saved.path,'utf8'),'Skills/guide/'+file);
|
||
}
|
||
assert.equal(attached.files.length,4);
|
||
});
|
||
|
||
test('续做时锁定版本在知识库已下线或换号,继续使用本地锁定资料;认证失败仍停止', async t => {
|
||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-pinned-gone-'));
|
||
t.after(()=>fs.rm(root,{recursive:true}));
|
||
const store={root,dir:root,appendEvent:async()=>{}};
|
||
const selection={resourceSetId:'pinned'};
|
||
const skill={fileId:'skill',revision:'1',path:'Skills/guide/SKILL.md',kind:'skill',text:'---\nname: guide\ndescription: Guide.\n---\n正文'};
|
||
await openEnterpriseSkills(store,selection,async()=>({skills:[skill],rules:[]}),()=>assert.fail('没有附件'));
|
||
for (const status of [404,410]) {
|
||
const reopened=await openEnterpriseSkills(store,selection,()=>assert.fail('续做不重新锁定'),undefined,
|
||
async()=>{ throw Object.assign(Error('企业知识库资料不存在或不可读取(HTTP '+status+')'),{status}); });
|
||
assert.match(reopened.versionNotice,/当前项目继续使用已锁定的版本/);
|
||
}
|
||
for (const status of [401,403]) {
|
||
await assert.rejects(openEnterpriseSkills(store,selection,()=>assert.fail('续做不重新锁定'),undefined,
|
||
async()=>{ throw Object.assign(Error('认证失败'),{status}); }),{status});
|
||
}
|
||
});
|
||
|
||
|
||
test('开工读取按 Pi 节奏有限重试,权限和资源状态立即返回', async () => {
|
||
const read=DetailPiAgent.prototype.productionKnowledgeRead.call({canvas:{read:async()=>({})}},'production');
|
||
for (const status of [401,403,404,410]) {
|
||
let attempted=0;
|
||
await assert.rejects(read(async()=>{ attempted++; throw Object.assign(Error('不可读取'),{status}); }),{status});
|
||
assert.equal(attempted,1);
|
||
}
|
||
let attempted=0;
|
||
const offline=Object.assign(Error('网络不可达'),{network:true});
|
||
const upstream=Object.assign(Error('服务维护'),{status:503});
|
||
const result=read(async()=>{
|
||
attempted++;
|
||
throw attempted % 2 ? offline : upstream;
|
||
});
|
||
await assert.rejects(result,{status:503});
|
||
assert.equal(attempted,4);
|
||
});
|