343 lines
22 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { createAssistantMessageEventStream, getCurrentSystemPrompt } from '@earendil-works/pi-ai/compat';
import { ProjectStore } from '../src/store.mjs';
import { evaluate, ToolLab } from '../src/tool-lab.mjs';
import { DetailPiAgent } from '../src/agent.mjs';
import { recordProductionExport } from '../src/production-goal.mjs';
import { EnterpriseContext } from '../src/enterprise-context.mjs';
import { projectTools } from '../src/project-tools.mjs';
import { openEnterpriseSkills } from '../src/enterprise-skill-resources.mjs';
import { mayContinueProductionGoal } from '../src/production-goal.mjs';
import { cleanup } from './cleanup.mjs';
const identity = () => ({ scope: 'a'.repeat(64), project: randomUUID() });
const binding = shop => ({ brandId: 'qa-brand', shopId: shop, categoryId: 'qa-desk', platform: 'qa-web', version: '1', source: 'explicit-local-qa-fixture', rules: [`仅使用${shop}的规则`] });
const root = () => fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-'));
function stream(content) {
const result = createAssistantMessageEventStream();
const message = { role: 'assistant', api: 'openai-completions', provider: 'jiansun-native-98k', model: 'qa-model', content, stopReason: content.some(c => c.type === 'toolCall') ? 'toolUse' : 'stop', timestamp: Date.now(), usage: { input: 10, output: 10, cacheRead: 0, cacheWrite: 0, totalTokens: 20, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
queueMicrotask(() => { result.push({ type: 'start', partial: message }); result.push({ type: 'done', reason: message.stopReason, message }); result.end(message); });
return result;
}
const info = scope => ({ accountScope: scope, model: { id: 'qa-model', protocol: 'openai-chat' }, pending: [] });
test('Pi production and its worker read the same locked Skill and its relative reference', async t => {
const dir=await root(), id=identity(), documentId=23;
t.after(()=>cleanup(dir));
const store=await ProjectStore.open(dir,id,binding('lights'));
const variantId=randomUUID(), runDeadline=Math.floor(Date.now()/1000)+300;
const selection={brandName:'试验品牌',categoryName:'灯具',templateId:'two-outputs',releaseId:'v4',
resourceSetId:'lighting',outputId:'detail',runDeadline};
const reference={fileId:'finish',revision:'r7',path:'Skills/lighting/references/finish.md'};
const knowledge={...selection,skillDirectory:'Skills',referenceSources:[reference],skills:[{fileId:'root',revision:'r4',kind:'skill',path:'Skills/lighting/SKILL.md',
text:'---\nname: lighting\ndescription: Use for lighting products.\n---\nUse the [fixture notes](references/finish.md).'}],
rules:[]};
const canvas={run:'skill-fixture',documentId,detailImages(){},begin:async()=>({run:'skill-fixture',conversationActive:true}),
read:async()=>({conversationActive:true,revision:1}),delta:async()=>{},activity:async()=>{},reply:async()=>{},end:async()=>{},
detailCopyFields:async()=>({fields:[]}),
workflowRead:async()=>({available:true,version:1,canvasFirst:true,outputId:'detail',productVariantId:variantId,totalSlots:1,
slots:[{id:'lighting-slot',fieldId:'lamp',label:'灯罩近景'}],
template:{id:'two-outputs',version:'v4',contentHash:'v4',enterprise:true,resourceSetId:'lighting'},
productEvidence:{accountScope:id.scope,project:id.project,documentId,brief:{brandName:'试验品牌',categoryName:'灯具'}}})};
let main=0,worker=0,serial=0;
const reads=new Map();
const transport={info:info(id.scope),stream(_model,context){
const system=getCurrentSystemPrompt(context.messages);
assert.match(system,/<name>lighting<\/name>/);
assert.doesNotMatch(system,/PINNED_FINISH|Use the \[fixture notes\]/);
const location=system.match(/<name>lighting<\/name>[\s\S]*?<location>([^<]*SKILL\.md)<\/location>/u)[1];
const child=system.includes('完成主代理委托的图位');
const steps=child?[
['read',{path:location}],
['read',{path:path.join(path.dirname(location),'references','finish.md')}],
]:[
['read',{path:location}],
['delegate_image_slots',{jobs:[{slotId:'lighting-slot',goal:'查看灯具的饰面规则'}]}],
['await_image_slots',{}],
['read',{path:path.join(path.dirname(location),'references','finish.md')}],
['finish_production',{revision:1}],
];
for(const result of context.messages.filter(message=>message.role==='toolResult'&&message.toolName==='read')){
assert.notEqual(result.isError,true,JSON.stringify(result.content));
reads.set(result.toolCallId,result.content.map(item=>item.text).join('\n'));
}
const step=steps[child?worker++:main++];
return step?stream([{type:'toolCall',name:step[0],id:'skill-'+(++serial),arguments:step[1]}]):
stream([{type:'text',text:'本轮结束。'}]);
}};
const host=await DetailPiAgent.open({store,canvas,transport,documentId,productionGoal:{outputId:'detail',variantId,workspaceId:randomUUID(),requestedOutputs:[{outputId:'detail',variantId}],deadline:runDeadline}});
let loads=0;
const documents=[];
host.enterpriseContext=new EnterpriseContext(store,{
call:async()=>assert.fail('a reference published with a version needs no catalogue search'),
readDocument:async(fileId,revision)=>{
documents.push([fileId,revision]);
return {result:{revision,text:'PINNED_FINISH: keep satin highlights.'}};
},
});
host.enterpriseContext.load=async()=>{loads++;return knowledge;};
try {
assert.equal((await host.prompt('制作详情页')).production.complete,true);
const context=await host.modelContext({}, {loadKnowledge:true});
assert.deepEqual(context.enterpriseKnowledge.sources.map(row=>row.revision),['r4','r7']);
assert.equal(loads,1,'read-only context uses the original locked selection');
assert.equal([...reads.values()].filter(body=>body.includes('fixture notes')).length,2);
assert.equal([...reads.values()].filter(body=>body.includes('PINNED_FINISH')).length,2);
assert.deepEqual(documents,[['finish','r7']]);
const second=await openEnterpriseSkills(store,selection,()=>{throw Error('run must use the first locked version');});
assert.equal(second.knowledge.rules[0].revision,'r7');
const mainSelection={...selection,outputId:'main_images',releaseId:'main-v4'};
const mainBinding=await openEnterpriseSkills(store,mainSelection,pins=>{
assert.equal(pins.get(knowledge.skills[0].path).revision,'r4');
assert.equal(pins.get(reference.path).revision,'r7');
return {...knowledge,...mainSelection,skills:[pins.get(knowledge.skills[0].path)],rules:[]};
},()=>assert.fail('sibling output must use the existing pin'));
assert.equal(mainBinding.resource.skills[0].filePath,second.resource.skills[0].filePath);
assert.equal(await mainBinding.resolveFile(path.join(path.dirname(mainBinding.resource.skills[0].filePath),'references','finish.md')),true);
const events=(await fs.readFile(path.join(store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(line=>JSON.parse(line));
assert.deepEqual(events.filter(e=>e.type==='enterprise_skill_resource_read').map(e=>[e.agent,e.fileId,e.revision]),
[['main','root','r4'],['worker','root','r4'],['worker','finish','r7'],['main','finish','r7']]);
} finally {await host.dispose();}
});
test('native read reports an unavailable linked document and can read it once published', async t => {
const dir=await root(), id=identity();
t.after(()=>cleanup(dir));
const store=await ProjectStore.open(dir,id,binding('finish'));
const selection={outputId:'detail'};
const knowledge={skillDirectory:'Skills',skills:[{fileId:'root',revision:'r4',kind:'skill',path:'Skills/lights/SKILL.md',
text:'---\nname: lights\ndescription: Lamp production.\n---\n[Finish](references/missing.md)'}],rules:[]};
const target='Skills/lights/references/missing.md';
let published=false, searchCalls=0, reads=0;
const client=new EnterpriseContext(store,{
async call(name,{directory,query}) {
assert.equal(name,'search_files');
assert.equal(directory,'Skills/lights/references');
assert.equal(query,'missing.md');
searchCalls++;
return {result:{entries:[
{id:'wrong',revision:'v1',path:'Skills/lights/unrelated/missing.md'},
...(published?[{id:'exact',revision:'r1',path:target}]:[]),
]}};
},
async readDocument(fileId,revision) {
assert.deepEqual([fileId,revision],['exact','r1']);
reads++;
return {result:{revision,text:'The exact published reference.'}};
},
});
const host={store,productionSkills:await openEnterpriseSkills(store,selection,async()=>knowledge,
(relative,lock)=>client.loadReference(relative,{...lock,read:execute=>execute()}))};
const {read}=await projectTools(host);
const skill=host.productionSkills.resource.skills[0].filePath;
const readMain=read('main'), readWorker=read('worker');
const file=path.join(path.dirname(skill),'references','missing.md');
await assert.rejects(readMain.execute('absent',{path:file}),/Skills\/lights\/SKILL\.md.*Skills\/lights\/references\/missing\.md/u);
await assert.rejects(fs.access(file),{code:'ENOENT'});
await assert.rejects(readMain.execute('unrelated',{path:path.join(path.dirname(file),'unrelated.md')}),/本项目工作目录之外/u);
assert.equal(searchCalls,1);
assert.match((await readMain.execute('entry',{path:skill})).content[0].text,/Lamp production/u);
published=true;
for(const reply of await Promise.all([readMain.execute('present',{path:file}),readWorker.execute('same',{path:file})])){
assert.equal(reply.content[0].text,'The exact published reference.');
}
assert.deepEqual([searchCalls,reads],[2,1]);
});
test('Pi continues the goal without a host readiness gate', async () => {
const host={productionGoal:{deadline:Date.now()/1000+60}};
for(let turn=0;turn<4;turn++)assert.equal(await mayContinueProductionGoal(host),true);
for(const stopReason of ['error','aborted']){
assert.equal(await mayContinueProductionGoal(host,{messages:[{role:'assistant',stopReason}]}),false);
}
host.goalStageResult={production:{complete:true}};
assert.equal(await mayContinueProductionGoal(host),false);
host.goalStageResult=null;
host.productionGoal.deadline=Date.now()/1000-1;
assert.equal(await mayContinueProductionGoal(host),false);
});
test('explicit tools share one Pi transcript and submit each real canvas revision', async t => {
const dir=await root(), id=identity();
t.after(()=>cleanup(dir));
const store=await ProjectStore.open(dir,id,binding('goal-shop'));
const variantId=randomUUID(), userText='制作详情、主图和 SKU';
const publicActivity=[],steps=[];
let stage,serial=0,revision=7,copyWrites=0;
const fields=[{layer:1,field:'title',page:'screen',currentText:''}];
const canvas={
run:'goal-fixture',documentId:13,detailImages(){},
begin:async()=>({run:'goal-fixture',conversationActive:true,context:null}),
read:async()=>({conversationActive:true,revision}),delta:async()=>{},end:async()=>{},
activity:async(_label,event)=>publicActivity.push(event),
workflowRead:async()=>({available:true,version:1,canvasFirst:true,outputId:stage,
productVariantId:variantId,totalSlots:0,slots:[],template:{contentHash:stage},
productEvidence:{accountScope:id.scope,project:id.project,documentId:13,brief:{}}}),
detailCopyFields:async()=>({fields:structuredClone(fields),revision}),
commitDetailCopy:async(items,expected)=>{
assert.equal(expected,revision);
assert.equal(items[0].expectedText,fields[0].currentText);
copyWrites++;
revision++;
fields[0].currentText=items[0].text;
return {appliedLayers:[1]};
},
};
const transport={info:info(id.scope),stream(_model,context){
const instructions=getCurrentSystemPrompt(context.messages);
assert.match(instructions,/由你决定要做什么、顺序、并行和返工/);
assert.match(instructions,/企业 Skill 中的命令行编修可在当前画布用等价的 PhotoCraft 原生命令完成/);
const call=steps.shift();
return call?stream([{type:'toolCall',name:call[0],id:'tool-'+(++serial),arguments:call[1]??{}}]):
stream([{type:'text',text:'当前进展已记在项目里。'}]);
}};
let savedGoal;
const workspaceId=randomUUID();
const requestedOutputs=['detail','main_images','sku_images'].map(outputId=>({outputId,variantId}));
for(const {outputId} of requestedOutputs){
stage=outputId;
const host=await DetailPiAgent.open({store,canvas,transport,documentId:13,
productionGoal:{outputId,variantId,workspaceId,requestedOutputs,deadline:Date.now()/1000+20}});
try {
steps.push(['plan_production'],['review_image_slots',{slotIds:[]}],null);
if(outputId==='main_images')steps.push(['read_copy_fields'],['write_copy_fields',{revision,items:[{
layer:1,text:'木纹沿桌面延伸',sources:['P01'],pictures:[],
}]}]);
steps.push(['finish_production',{revision:revision+Number(outputId==='main_images')}]);
const text=savedGoal?'导出回执提醒检查当前画布':userText;
const result=await host.prompt(text,{goalContinuation:!!savedGoal});
assert.equal(result.production.outputId,outputId);
assert.equal(result.production.canvasRevision,revision);
assert.equal(result.production.complete,true);
savedGoal??=result.production.piGoalId;
assert.equal(result.production.piGoalId,savedGoal);
const entries=host.manager.getEntries();
assert.deepEqual(entries.filter(e=>e.type==='custom_message'&&e.customType==='photocraft-goal-request').map(e=>JSON.parse(e.content).request),[userText]);
assert.ok(entries.some(e=>e.type==='custom_message'&&e.customType==='pi-goal-event'&&e.details.kind==='continuation'));
if(outputId!=='detail')assert.ok(entries.some(e=>e.type==='custom_message'&&e.customType==='photocraft-goal-stage'&&e.content===text));
}finally{await host.dispose();}
}
assert.equal(copyWrites,1);
assert.ok(publicActivity.every(row=>row.scope.documentId===canvas.documentId&&row.scope.run===canvas.run));
assert.deepEqual(await recordProductionExport(store.dir,savedGoal),{recorded:true,goalId:savedGoal});
const chat=await DetailPiAgent.open({store,canvas,transport});
try{
assert.equal(chat.session.getToolDefinition('finish_production'),undefined);
assert.equal(chat.manager.getEntries().findLast(e=>e.type==='custom'&&e.customType==='pi-goal').data.goal.status,'complete');
}finally{await chat.dispose();}
});
test('generated tools have no Node/FS/network and cannot run forever', async () => {
assert.deepEqual(await evaluate('function main(){return [typeof process,typeof require,typeof fetch,typeof Deno]}', {}), ['undefined', 'undefined', 'undefined', 'undefined']);
await assert.rejects(evaluate('function main(){while(true){}}', {}, 30), /隔离工具失败/);
await assert.rejects(evaluate('function main(){return import("node:fs")}', {}), /工具必须返回|隔离工具失败/);
assert.equal(await evaluate('function main(a){return a.x+1}', { x: 2 }), 3);
});
test('only tested immutable tool versions execute; failed tests cannot replace', async () => {
const dir = await root(), lab = new ToolLab(dir);
const args = { name: 'add_one', description: 'QA', source: 'function main(i){return i+1}', tests: [{ input: 0, expected: 1 }, { input: -1, expected: 0 }, { input: 10, expected: 11 }] };
const saved = await lab.develop(args);
assert.equal((await lab.run('add_one', 4)).result, 5);
await assert.rejects(lab.develop({ ...args, source: 'function main(i){return i+2}' }), /测试1未通过/);
assert.equal((await lab.run('add_one', 4)).version, saved.version);
await assert.rejects(lab.run('../other', {}), /名称无效/);
await cleanup(dir);
});
test('snapshots, memories, sessions are isolated by account/shop/category/version', async () => {
const dir = await root(), id = identity();
const a = await ProjectStore.open(dir, id, binding('A'));
await a.recordUserEvidence('产品颜色是米白');
await a.remember({ key: 'color', value: '米白', evidence: '颜色是米白' }, [{ role: 'user', content: '产品颜色是米白' }]);
await a.recordUserEvidence('产品改为胡桃色');
await a.remember({ key: 'color', value: '胡桃', evidence: '改为胡桃色' }, [{ role: 'user', content: '产品改为胡桃色' }]);
assert.equal((await a.context()).confirmedMemory.color.previous, '米白');
await assert.rejects(a.remember({ key: 'certified', value: '已认证', evidence: '已认证测试' }, []), /用户已明确/);
const b = await ProjectStore.open(dir, id, binding('B'));
assert.notEqual(a.dir, b.dir);
assert.deepEqual((await b.context()).confirmedMemory, {});
const restored = await ProjectStore.open(dir, id, binding('A'));
assert.equal((await restored.context()).confirmedMemory.color.value, '胡桃');
const other = await ProjectStore.open(dir, { ...id, scope: 'b'.repeat(64) }, binding('A'));
assert.deepEqual((await other.context()).confirmedMemory, {});
await cleanup(dir);
});
test('actual Pi SDK executes memory tools, persists full transcript and reads project facts explicitly after restart', async () => {
const dir = await root(), id = identity(), store = await ProjectStore.open(dir, id, binding('A'));
let calls = 0;
const transport = { info: info(id.scope), stream(model, ctx) {
assert.doesNotMatch(getCurrentSystemPrompt(ctx.messages), /"shopId":"A"/);
calls++;
if (calls === 1) return stream([{ type: 'toolCall', id: 'qa-call-1', name: 'memory_set', arguments: { key: 'color', value: '胡桃色', evidence: '颜色是胡桃色' } }]);
if (calls === 3) return stream([{ type:'toolCall', id:'qa-read-context', name:'context_read', arguments:{} }]);
if (calls === 4) {
const evidence=ctx.messages.find(message=>message.role==='toolResult'&&message.toolName==='context_read');
assert.match(evidence.content[0].text, /"shopId":"A"/);
assert.match(evidence.content[0].text, /"color"/);
}
return stream([{ type: 'text', text: '已记录胡桃色' }]);
} };
let host = await DetailPiAgent.open({ store, transport });
assert.deepEqual(host.session.getActiveToolNames().sort(),
['bash','codemode','context_read','edit','find','grep','ls','memory_search','memory_set','read','tool_search','write']);
await host.prompt('这个测试产品颜色是胡桃色,请记住。');
const messages = host.session.messages.length, entries = host.manager.getEntryCount();
await host.dispose();
host = await DetailPiAgent.open({ store, transport });
assert.equal(host.session.messages.length, messages);
assert.equal(host.manager.getEntryCount(), entries);
await host.prompt('继续:颜色是什么?');
assert.equal(host.session.settingsManager.getRetryEnabled(), true);
await host.dispose(); await cleanup(dir);
});
test('an unresolved inference does not block a new prompt or replay an old tool', async () => {
const dir = await root(), id = identity(), store = await ProjectStore.open(dir, id, binding('A'));
let calls = 0;
const transport = { info: info(id.scope), stream() { calls++; return stream([{ type:'text',text:'x' }]); } };
const broker = { info: async () => ({ ...info(id.scope), pending: [{ id: 'original', phase: 'unknown' }] }) };
const host = await DetailPiAgent.open({ store, broker, transport });
assert.equal((await host.prompt('新一轮请求')).text,'x');
assert.equal(calls, 1);
await host.dispose(); await cleanup(dir);
});
test('references enter the actual Pi user message as image and quoted text parts', async () => {
const dir = await root(), id = identity(), store = await ProjectStore.open(dir, id, binding('A'));
const delivered = [];
const host = await DetailPiAgent.open({ store, transport: { info: info(id.scope), stream(_model, context) {
delivered.push(context.messages.findLast(message => message.role === 'user'));
return stream([{ type: 'text', text: '收到引用' }]);
} } });
try {
const data = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA0JCgsKCA0LCgsODg0PEyAVExISEyccHhcgLikxMC4pLSwzOko+MzZGNywtQFdBRkxOUlNSMj5aYVpQYEpRUk//2wBDAQ4ODhMREyYVFSZPNS01T09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0//wAARCAAIAAgDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAX/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAABAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCGAAoP/9k=';
await host.prompt('图里有什么?', { referenceContent: [{ label: '主图', image: data }, { label: '标题', text: '朴然 Pro' }] });
assert.equal(delivered.length, 1);
const { content } = delivered[0];
assert.deepEqual(content.find(part => part.type === 'image'), { type: 'image', mimeType: 'image/jpeg', data });
assert.match(content[0].text, /图里有什么/);
assert.match(content[0].text, /朴然 Pro/);
} finally {
await host.dispose();
await cleanup(dir);
}
});
test('actual Pi SDK retries an overloaded inference with the default budget', async () => {
const dir = await root(), id = identity(), store = await ProjectStore.open(dir, id, binding('A'));
let calls = 0;
const host = await DetailPiAgent.open({ store, transport: { info: info(id.scope), stream(model) {
calls++;
if (calls>1) return stream([{type:'text',text:'已接续。'}]);
const out = createAssistantMessageEventStream();
const error = { role: 'assistant', api: model.api, provider: model.provider, model: model.id, content: [], stopReason: 'error', errorMessage: 'HTTP 503 overload; original outcome unknown', timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
queueMicrotask(() => { out.push({ type: 'error', reason: 'error', error }); out.end(error); });
return out;
} } });
assert.equal((await host.prompt('继续处理')).text,'已接续。');
assert.equal(calls, 2);
assert.ok(host.manager.getEntries().some(e => e.type === 'message' && e.message.role === 'user'));
await host.dispose(); await cleanup(dir);
});