Support explicit current-output A/B fill, protected edited drafts, scoped cloud update offers and atomic native restore with stale-open CAS. Preserve original unknown requests, improve Pi conversation continuity and native DPI/navigation reads, and publish the authenticated template metadata contract. Validated: native backend 172 passed/5 environment tests ignored, UI 110, Pi 53, template/rule API 24 and native cloud contract 6; strict Clippy, layering and wasm. Real S01 selected B, edited/undo-redo, PCraft reopen and layered PSD roundtrip pass with exact pixels. Full nine-output generation and Photoshop acceptance remain open.
277 lines
24 KiB
JavaScript
277 lines
24 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 {DetailPiAgent} from '../src/agent.mjs';
|
||
import {ProjectStore,atomic} from '../src/store.mjs';
|
||
import {productContext} from '../src/project-context.mjs';
|
||
import {cleanup} from './cleanup.mjs';
|
||
|
||
const scope='6'.repeat(64),binding=shop=>({brandId:shop,shopId:shop,categoryId:'desk',platform:'native',version:'1',source:'explicit-local-test',brandName:shop,rules:[shop==='unconfigured'?'品牌规则未配置,不编造品牌规范':shop+'专属规则']});
|
||
const evidence=(project,color='胡桃色')=>({accountScope:scope,project,documentId:7,revision:2,brief:{name:'测试电脑桌',colorName:color,dimensions:{length:'',width:'',height:'',unit:'mm'}},facts:{status:'ready',items:[{text:'长方形桌面',source:'已核对实拍'}],missing:['尺寸、承重、木种未确认']},sellingPoints:{selected:['batch:0'],batches:[{id:'batch',items:['长方形桌面']}],stale:false},plan:{status:'confirmed',screens:[{name:'首屏',body:'展示当前产品',imagePrompt:'不得重复注入的大段生图提示'.repeat(1000)}]}});
|
||
const sse=(delta,finish='stop')=>`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta,finish_reason:null}]})}\n\ndata: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta:{},finish_reason:finish}]})}\n\ndata: [DONE]\n\n`;
|
||
const tool=(name,args)=>sse({tool_calls:[{index:0,id:randomUUID(),type:'function',function:{name,arguments:JSON.stringify(args)}}]},'tool_calls');
|
||
function canvas(){
|
||
return {revision:1,allowed:false,writeBlocked:false,writes:0,requests:0,text:'原始标题',
|
||
async begin(){this.allowed=false;this.writeBlocked=false;},
|
||
async read(){return {conversationActive:true,allowed:this.allowed,writeBlocked:this.writeBlocked,revision:this.revision,context:{id:7,name:'test',width:1440,height:1800,layers:[{id:1,name:'S01 title',kind:'Type',text:this.text,locked:{}}],product:{mustNotDuplicate:'private'}}};},
|
||
async requestWrite(revision){this.requests++;if(this.writeBlocked||revision!==this.revision)throw Error('用户已接手,写入未获许可');this.allowed=true;return this.read();},
|
||
async edit(edit,revision){assert.ok(this.allowed&&!this.writeBlocked);assert.equal(revision,this.revision);this.writes++;this.text=edit.params.text;this.revision++;return this.read();},
|
||
async delta(){},async activity(){},async end(){this.allowed=false;}};
|
||
}
|
||
async function fixture(reply,{shop='unconfigured'}={}){
|
||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),project=randomUUID(),identity={scope,project},store=await ProjectStore.open(root,identity,binding(shop),{continuous:true});
|
||
const requests=[],native=canvas(),events=[];
|
||
const broker={info:async()=>({accountScope:scope,model:{id:'qa',protocol:'openai-chat'},pending:[]}),round(){const id=randomUUID();return {id,fetch:async(_url,init)=>{const payload=JSON.parse(init.body);requests.push(payload);const response=reply(payload,requests.length,native);return response instanceof Response?response:new Response(response,{headers:{'content-type':'text/event-stream'}});},finish:async()=>({phase:'complete'})};}};
|
||
let host=await DetailPiAgent.open({store,broker,canvas:native,projectEvidence:evidence(project),documentId:7,onEvent:e=>events.push(e)});
|
||
return {root,identity,store,broker,native,requests,events,get host(){return host;},async reopen(shop,color='胡桃色'){await host.dispose();const next=await ProjectStore.open(root,identity,binding(shop),{continuous:true});host=await DetailPiAgent.open({store:next,broker,canvas:native,projectEvidence:evidence(project,color),documentId:7,onEvent:e=>events.push(e)});return next;},async close(){await host.dispose();await cleanup(root);}};
|
||
}
|
||
|
||
test('three plain native-wire turns discuss product facts without JSON or a canvas write grant',async()=>{
|
||
const x=await fixture(()=>sse({content:'可以先讨论布局。尺寸、承重与木种尚未确认。'}));
|
||
try{
|
||
for(const prompt of ['先聊一下这款产品的页面思路','为什么这样排?尺寸和承重能写吗?','给我两个表达方向,先不修改画布'])assert.match((await x.host.prompt(prompt)).text,/先讨论/);
|
||
assert.equal(x.requests.length,3);assert.equal(x.native.requests,0);assert.equal(x.native.writes,0);
|
||
assert.ok(x.events.some(e=>e.type==='text_delta'));
|
||
for(const payload of x.requests){
|
||
assert.equal(payload.tool_choice,'auto');assert.equal(payload.response_format,undefined);
|
||
const system=payload.messages.filter(m=>m.role==='system').map(m=>m.content).join('\n');
|
||
assert.equal(system.split('"currentProduct":').length-1,1);
|
||
assert.ok(system.includes('尺寸、承重、木种未确认'));assert.ok(system.includes('胡桃色'));assert.ok(system.includes('未配置'));
|
||
assert.ok(!system.includes('不得重复注入的大段生图提示'));assert.ok(!system.includes('mustNotDuplicate'));
|
||
}
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('project conversation survives restart and first rule binding while old-domain memory is not reinjected',async()=>{
|
||
const x=await fixture(()=>sse({content:'当前资料以本轮注入为准。'}));
|
||
try{
|
||
await x.host.prompt('颜色是胡桃色,风格安静,先讨论。');
|
||
await x.store.remember({key:'color',value:'胡桃色',evidence:'颜色是胡桃色'},x.host.session.messages);
|
||
await x.host.lab.develop({name:'old_shop_tool',description:'old domain test',source:'function main(i){return i+1}',tests:[{input:0,expected:1},{input:1,expected:2},{input:-1,expected:0}]});
|
||
await x.host.prompt('继续比较刚才的方案。');
|
||
const originalDir=x.store.dir,next=await x.reopen('configured-shop','米白');
|
||
assert.equal(next.dir,originalDir);assert.deepEqual((await next.context()).confirmedMemory,{});
|
||
assert.equal((await x.store.context()).confirmedMemory.color.value,'胡桃色','original rule-domain evidence remains available in its original file');
|
||
await assert.rejects(x.host.lab.run('old_shop_tool',1),/ENOENT/,'a tool from the old rule domain is not silently reused');
|
||
const foreign=await ProjectStore.open(x.root,{scope:'7'.repeat(64),project:x.identity.project},binding('configured-shop'),{continuous:true});
|
||
const otherProject=await ProjectStore.open(x.root,{scope,project:randomUUID()},binding('configured-shop'),{continuous:true});
|
||
assert.notEqual(foreign.dir,next.dir);assert.notEqual(otherProject.dir,next.dir);assert.deepEqual((await foreign.context()).confirmedMemory,{});
|
||
await x.host.prompt('接着刚才的讨论,现在颜色以米白为准,为什么?');
|
||
const payload=x.requests.at(-1),all=JSON.stringify(payload.messages);
|
||
assert.ok(all.includes('继续比较刚才的方案'));assert.ok(all.includes('颜色是胡桃色'));
|
||
const system=payload.messages.filter(m=>m.role==='system').map(m=>m.content).join('\n');
|
||
assert.ok(system.includes('米白'));assert.ok(system.includes('configured-shop专属规则'));
|
||
assert.ok(!system.includes('"evidence":"颜色是胡桃色"'),'old memory cannot become current confirmed memory on a rule change');
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('discussion followed by explicit editing requests permission only for the actual write',async()=>{
|
||
const x=await fixture((_payload,n,native)=>{
|
||
if(n<3)return sse({content:'先讨论,不修改。'});
|
||
if(n===3)return tool('canvas_read',{});
|
||
if(n===4)return tool('canvas_edit',{revision:native.revision,command:'type.edit',params:{layer:1,text:'新标题'},label:'修改标题'});
|
||
return sse({content:'已按要求修改标题。'});
|
||
});
|
||
try{
|
||
await x.host.prompt('讨论一下配色');await x.host.prompt('解释一下你的建议');assert.equal(x.native.requests,0);
|
||
await x.host.prompt('把当前标题改为新标题');
|
||
assert.equal(x.native.requests,1);assert.equal(x.native.writes,1);assert.equal(x.native.text,'新标题');
|
||
assert.ok(x.requests[3].messages.some(m=>m.role==='tool'&&m.content.includes('"writeBlocked":false')));
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('current-domain memory requires the user to reconfirm old-shop evidence even when it remains in continuous history',async()=>{
|
||
const evidence='当前商品颜色是胡桃色';
|
||
const x=await fixture((_payload,n)=>[2,4].includes(n)?tool('memory_set',{key:'color',value:'胡桃色',evidence}):sse({content:'按当前域明确确认的资料处理。'}),{shop:'old-shop'});
|
||
try{
|
||
await x.host.prompt(evidence+',先讨论旧店铺。');
|
||
const next=await x.reopen('new-shop');
|
||
assert.ok(x.host.session.messages.some(m=>m.role==='user'&&(typeof m.content==='string'?m.content.includes(evidence):m.content.some(c=>c.type==='text'&&c.text.includes(evidence)))));
|
||
await x.host.prompt('现在只讨论新店铺的布局,尚未确认旧资料适用于这里。');
|
||
assert.deepEqual((await next.context()).confirmedMemory,{});
|
||
assert.ok(x.host.session.messages.some(m=>m.role==='toolResult'&&m.toolName==='memory_set'&&m.isError));
|
||
await x.host.prompt('我重新确认:'+evidence+',适用于当前店铺,请记住。');
|
||
const memory=(await next.context()).confirmedMemory.color;
|
||
assert.equal(memory.value,'胡桃色');assert.equal(memory.bindingHash,next.hash);assert.equal(memory.evidence,evidence);
|
||
const oldLedger=await fs.readFile(path.join(x.store.memoryDir,'user-evidence.jsonl'),'utf8');
|
||
const newLedger=await fs.readFile(path.join(next.memoryDir,'user-evidence.jsonl'),'utf8');
|
||
assert.ok(oldLedger.includes('旧店铺'));assert.ok(!newLedger.includes('先讨论旧店铺'));
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('an inactive project cannot read another canvas through a tool or dispatch a new discussion using its context',async()=>{
|
||
const x=await fixture(()=>sse({content:'A项目的原回复留存。'}));
|
||
try{
|
||
await x.host.prompt('先讨论A产品,不修改。');
|
||
x.native.read=async()=>({conversationActive:false,allowed:false,writeBlocked:true,revision:99,context:{id:8,name:'B项目私有名称',width:750,layers:[{id:91,text:'B的秘密文字'}]}});
|
||
const read=x.host.session.agent.state.tools.find(t=>t.name==='canvas_read');
|
||
await assert.rejects(read.execute('inactive-read',{},undefined),/项目已切换/);
|
||
await assert.rejects(x.host.prompt('仍来自A的迟到要求'),/项目已切换/);
|
||
assert.equal(x.requests.length,1);assert.ok(!JSON.stringify(x.requests).includes('B的秘密文字'));
|
||
assert.ok(x.host.manager.getEntries().some(e=>e.type==='message'&&e.message.role==='assistant'&&e.message.content.some(c=>c.text==='A项目的原回复留存。')));
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('switching projects in the middle of the original SSE detaches UI delivery but keeps the complete A reply with one POST',async()=>{
|
||
const fragments=['A开始讨论。','A继续解释,保留这一段。','A结尾完整信息。'],full=fragments.join('');
|
||
let chunksConsumed=0,deltaAttempts=0,endAttempts=0,switched=false;const otherProjectHistory=[];
|
||
const x=await fixture(()=>new Response(new ReadableStream({async start(controller){
|
||
for(const content of fragments){controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta:{content},finish_reason:null}]})}\n\n`));chunksConsumed++;await new Promise(r=>setTimeout(r,30));}
|
||
controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta:{},finish_reason:'stop'}]})}\n\ndata: [DONE]\n\n`));controller.close();
|
||
}}),{headers:{'content-type':'text/event-stream'}}));
|
||
const originalRead=x.native.read.bind(x.native);
|
||
x.native.read=async()=>switched?{conversationActive:false,allowed:false,writeBlocked:true,context:null}:originalRead();
|
||
x.native.delta=async()=>{deltaAttempts++;switched=true;throw Error('原项目已切换,回复保留在原项目会话,未写入当前项目');};
|
||
x.native.activity=async text=>{otherProjectHistory.push(text);throw Error('must not deliver activity into B');};
|
||
x.native.end=async()=>{endAttempts++;throw Error('原项目已切换,回复保留在原项目会话,未写入当前项目');};
|
||
try{
|
||
const result=await x.host.prompt('A项目:完整解释后自然结束,不修改画布。');
|
||
assert.equal(result.text,full);assert.equal(result.rounds,1);assert.equal(x.requests.length,1);assert.equal(chunksConsumed,3);
|
||
assert.equal(deltaAttempts,1);assert.equal(endAttempts,1);assert.deepEqual(otherProjectHistory,[]);assert.equal(x.native.writes,0);
|
||
const replies=x.host.manager.getEntries().filter(e=>e.type==='message'&&e.message.role==='assistant').map(e=>e.message);
|
||
assert.ok(replies.some(m=>m.stopReason==='stop'&&m.content.filter(c=>c.type==='text').map(c=>c.text).join('')===full));
|
||
assert.ok(!replies.some(m=>m.stopReason==='error'),'an inactive display is not an incomplete model result');
|
||
const journal=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).split('\n').filter(Boolean).map(JSON.parse);
|
||
assert.equal(journal.filter(e=>e.type==='provider_prepared').length,1);assert.ok(journal.some(e=>e.type==='provider_finished'&&e.phase==='complete'));
|
||
assert.ok(journal.some(e=>e.type==='inactive_ui_delivery'&&e.method==='delta'));assert.ok(journal.some(e=>e.type==='inactive_ui_delivery'&&e.method==='end'));
|
||
assert.equal(x.events.filter(e=>e.type==='text_delta').map(e=>e.delta).join(''),full);
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('inactive activity delivery preserves the original assistant/tool transcript and stops the next paid model step locally',async()=>{
|
||
let activityAttempts=0,endAttempts=0,switched=false;const otherProjectHistory=[];
|
||
const x=await fixture(()=>sse({content:'A的完整规则解释,随后只读查询原历史。',tool_calls:[{index:0,id:'read-old-a',type:'function',function:{name:'memory_search',arguments:JSON.stringify({query:'A项目'})}}]},'tool_calls'));
|
||
const originalRead=x.native.read.bind(x.native);
|
||
x.native.read=async()=>switched?{conversationActive:false,allowed:false,writeBlocked:true,context:null}:originalRead();
|
||
x.native.activity=async()=>{activityAttempts++;switched=true;throw Error('当前项目已切换,未向其他项目投递操作说明');};
|
||
x.native.delta=async text=>{if(switched)otherProjectHistory.push(text);};
|
||
x.native.end=async()=>{endAttempts++;throw Error('原项目已切换,回复保留在原项目会话,未写入当前项目');};
|
||
try{
|
||
const result=await x.host.prompt('A项目:解释当前规则,并只读查找A项目的历史。');
|
||
assert.match(result.text,/原项目已切换/);assert.equal(x.requests.length,1);assert.equal(result.rounds,1);
|
||
assert.equal(activityAttempts,1);assert.equal(endAttempts,1);assert.deepEqual(otherProjectHistory,[]);assert.equal(x.native.requests,0);assert.equal(x.native.writes,0);
|
||
const messages=x.host.manager.getEntries().filter(e=>e.type==='message').map(e=>e.message);
|
||
assert.ok(messages.some(m=>m.role==='assistant'&&m.stopReason==='toolUse'&&m.content.some(c=>c.type==='text'&&c.text==='A的完整规则解释,随后只读查询原历史。')));
|
||
assert.ok(messages.some(m=>m.role==='toolResult'&&m.toolCallId==='read-old-a'&&!m.isError));
|
||
assert.ok(!messages.some(m=>m.role==='assistant'&&m.stopReason==='error'));
|
||
const log=await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8');assert.ok(log.includes('inactive_project_stopped'));
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('UI detachment never swallows transport or account errors and never retries a sent end',async()=>{
|
||
for(const [method,message] of [['delta','画布连接中断,原操作需核查'],['activity','本地Agent会话或账户已改变'],['end','画布连接中断,结束动作结果未知']]){
|
||
let attempts=0;
|
||
const x=await fixture(()=>method==='activity'?tool('memory_search',{query:'讨论'}):sse({content:'原回复。'}));
|
||
x.native[method]=async()=>{attempts++;throw Error(message);};
|
||
try{
|
||
await assert.rejects(x.host.prompt('当前项目普通讨论'),new RegExp(message));
|
||
assert.equal(attempts,1);assert.equal(x.requests.length,1);assert.notEqual(x.host.canvasNotificationsDetached,true);
|
||
}finally{await x.close();}
|
||
}
|
||
});
|
||
|
||
test('handover rejects the proposed write and skips subsequent editing inference, then a new question works',async()=>{
|
||
const x=await fixture((_payload,n,native)=>{
|
||
if(n===1)return tool('canvas_read',{});
|
||
if(n===2){native.writeBlocked=true;return tool('canvas_edit',{revision:native.revision,command:'type.edit',params:{layer:1,text:'不可应用'},label:'修改标题'});}
|
||
return sse({content:'新的问答可以继续,上一轮修改已经停止。'});
|
||
});
|
||
try{
|
||
assert.match((await x.host.prompt('请改标题,过程中用户接手')).text,/已接手/);
|
||
assert.equal(x.requests.length,2);assert.equal(x.native.writes,0);assert.equal(x.native.text,'原始标题');
|
||
assert.match((await x.host.prompt('先不修改,继续解释另一个方案')).text,/新的问答/);
|
||
assert.equal(x.requests.length,3);assert.equal(x.native.writes,0);
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('a canvas click during discussion blocks writes but does not cut off a read-only discussion or its streamed reply',async()=>{
|
||
const x=await fixture((_payload,n,native)=>{
|
||
if(n===1){native.writeBlocked=true;return tool('context_read',{});}
|
||
return sse({content:'可以继续完整讨论:先用真实外观建立首屏,再解释产品细节。尺寸未确认,所以不写具体数值。'});
|
||
});
|
||
try{
|
||
const result=await x.host.prompt('先讨论页面顺序,不修改画布;我会手动点选查看产品。');
|
||
assert.match(result.text,/可以继续完整讨论/);assert.match(result.text,/不写具体数值/);
|
||
assert.equal(x.requests.length,2);assert.equal(x.native.requests,0);assert.equal(x.native.writes,0);
|
||
assert.ok(x.native.writeBlocked);assert.ok(x.events.some(e=>e.type==='text_delta'&&e.delta.includes('完整讨论')));
|
||
const system=x.requests[1].messages.filter(m=>m.role==='system').map(m=>m.content).join('\n');
|
||
assert.ok(system.includes('"writeBlocked":true'));
|
||
assert.ok(!x.host.session.messages.some(m=>m.role==='assistant'&&m.content?.some(c=>c.type==='text'&&c.text==='本机:已接手,剩余画布操作已停止。')));
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('compact product evidence is bounded, omits visual prompts and rejects foreign identity',()=>{
|
||
const project=randomUUID(),source=evidence(project);
|
||
source.facts.items=Array.from({length:100},()=>({text:'事实'.repeat(500),source:'来源'.repeat(500)}));source.facts.missing=Array.from({length:100},()=> '待确认'.repeat(500));
|
||
const context=productContext(source,{scope,project,documentId:7});
|
||
assert.ok(JSON.stringify(context).length<=14000);assert.ok(context.omitted.facts>0);assert.ok(context.omitted.missing>0);
|
||
assert.ok(!JSON.stringify(context).includes('imagePrompt'));
|
||
for(const identity of [{scope:'7'.repeat(64),project,documentId:7},{scope,project:randomUUID(),documentId:7},{scope,project,documentId:8}])assert.throws(()=>productContext(source,identity),/不属于/);
|
||
});
|
||
|
||
test('legacy transcript migration retains originals and never clears broker pending on a binding change',async()=>{
|
||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),identity={scope,project:randomUUID()};let host;
|
||
try{
|
||
const legacy=await ProjectStore.open(root,identity,binding('A'));
|
||
const {SessionManager}=await import('@earendil-works/pi-coding-agent');
|
||
const manager=SessionManager.create(legacy.dir,path.join(legacy.dir,'sessions'));
|
||
manager.appendMessage({role:'user',content:'原始会话必须保留',timestamp:Date.now()});
|
||
await atomic(path.join(legacy.dir,'session.json'),{file:manager.getSessionFile()});
|
||
await legacy.appendEvent({type:'provider_prepared',id:'preserved-request',bindingHash:legacy.hash});
|
||
await atomic(path.join(legacy.dir,'recovered-tools.json'),[{id:'preserved-request',phase:'review'}]);
|
||
const original=await fs.readFile(manager.getSessionFile(),'utf8');
|
||
const stable=await ProjectStore.open(root,identity,binding('B'),{continuous:true});
|
||
assert.deepEqual(await stable.get('recovered-tools.json',[]),[{id:'preserved-request',phase:'review'}]);
|
||
assert.ok((await fs.readFile(path.join(stable.dir,'events.jsonl'),'utf8')).includes('preserved-request'));
|
||
let posts=0;
|
||
host=await DetailPiAgent.open({store:stable,broker:{info:async()=>({accountScope:scope,model:{id:'qa',protocol:'openai-chat'},pending:[{id:'original-unknown'}]}),round(){posts++;throw Error('must not post');}}});
|
||
assert.ok(host.session.messages.some(m=>m.role==='user'&&m.content==='原始会话必须保留'));
|
||
await assert.rejects(host.prompt('继续普通聊天也不能重发未知请求'),/未知请求|工具建议/);assert.equal(posts,0);
|
||
assert.equal(await fs.readFile(manager.getSessionFile(),'utf8'),original);
|
||
}finally{await host?.dispose();await cleanup(root);}
|
||
});
|
||
|
||
test('legacy migration resumes exact partially copied files and publishes the pointer last without overwriting originals',async()=>{
|
||
for(const copiedEvents of [false,true]){
|
||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),identity={scope,project:randomUUID()};
|
||
try{
|
||
const legacy=await ProjectStore.open(root,identity,binding('legacy-shop'));
|
||
const {SessionManager}=await import('@earendil-works/pi-coding-agent');
|
||
const manager=SessionManager.create(legacy.dir,path.join(legacy.dir,'sessions'));
|
||
manager.appendMessage({role:'user',content:'迁移原件不得改写',timestamp:Date.now()});
|
||
await atomic(path.join(legacy.dir,'session.json'),{file:manager.getSessionFile()});
|
||
await legacy.appendEvent({type:'provider_prepared',id:'old-request',bindingHash:legacy.hash});
|
||
await atomic(path.join(legacy.dir,'recovered-tools.json'),[{id:'old-request',phase:'review'}]);
|
||
const original=await fs.readFile(manager.getSessionFile()),events=await fs.readFile(path.join(legacy.dir,'events.jsonl'));
|
||
const stableDir=path.join(legacy.root,'conversation-v1'),target=path.join(stableDir,'sessions','legacy-'+legacy.hash+'.jsonl');
|
||
await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,original,{flag:'wx'});
|
||
if(copiedEvents)await fs.writeFile(path.join(stableDir,'events.jsonl'),events,{flag:'wx'});
|
||
const resumed=await ProjectStore.open(root,identity,binding('new-shop'),{continuous:true});
|
||
assert.equal((await resumed.get('session.json')).file,target);assert.deepEqual(await fs.readFile(target),original);
|
||
assert.deepEqual(await fs.readFile(manager.getSessionFile()),original);assert.deepEqual(await fs.readFile(path.join(stableDir,'events.jsonl')),events);
|
||
assert.deepEqual(await resumed.get('recovered-tools.json'),[{id:'old-request',phase:'review'}]);
|
||
assert.equal((await resumed.get('migration.json')).originalRetained,true);
|
||
await ProjectStore.open(root,identity,binding('new-shop'),{continuous:true});
|
||
assert.deepEqual(await fs.readFile(target),original);
|
||
}finally{await cleanup(root);}
|
||
}
|
||
});
|
||
|
||
test('legacy migration rejects a pre-existing target with different bytes and never publishes a pointer or overwrites it',async()=>{
|
||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),identity={scope,project:randomUUID()};
|
||
try{
|
||
const legacy=await ProjectStore.open(root,identity,binding('legacy-shop'));
|
||
const {SessionManager}=await import('@earendil-works/pi-coding-agent');
|
||
const manager=SessionManager.create(legacy.dir,path.join(legacy.dir,'sessions'));
|
||
manager.appendMessage({role:'user',content:'原件',timestamp:Date.now()});await atomic(path.join(legacy.dir,'session.json'),{file:manager.getSessionFile()});
|
||
const original=await fs.readFile(manager.getSessionFile()),stableDir=path.join(legacy.root,'conversation-v1'),target=path.join(stableDir,'sessions','legacy-'+legacy.hash+'.jsonl');
|
||
await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,'different retained bytes',{flag:'wx'});
|
||
await assert.rejects(ProjectStore.open(root,identity,binding('new-shop'),{continuous:true}),/迁移目标与原件不一致/);
|
||
assert.equal(await fs.readFile(target,'utf8'),'different retained bytes');assert.deepEqual(await fs.readFile(manager.getSessionFile()),original);
|
||
await assert.rejects(fs.access(path.join(stableDir,'session.json')),error=>error.code==='ENOENT');
|
||
}finally{await cleanup(root);}
|
||
});
|