gongxiangp2/apps/detail-agent-pi/test/project-repository.test.mjs

386 lines
21 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import test from 'node:test';
import { openProductionOperations } from '../src/production-operations.mjs';
import { completeCanvas } from './fake-canvas.mjs';
import { ProjectRepository } from '../src/project-repository.mjs';
import { recordProductionInputs } from '../src/production-repository.mjs';
import { cleanup } from './cleanup.mjs';
import { productionStore } from './production-store-fixture.mjs';
const scope = { accountId: 'account', projectId: 'project', outputId: 'detail', variantId: 'oak' };
const binding = '["template","oak"]';
const hash = value => createHash('sha256').update(value).digest('hex');
const request = (requestId = 'image-a', spec = { prompt: '用同款实拍约束轮廓。' }) => ({
requestId, operationId: `operation-${requestId}`, requestSpecHash: hash(JSON.stringify(spec)),
revision: 1, slotId: 'front', binding, spec,
});
const approve = draft => ({
requestId: draft.requestId, expectedHash: draft.requestSpecHash, expectedRevision: draft.revision,
});
function seedLegacyRequest(repo, draft, state='prepared', receipt=null) {
repo.readLedger();
const db=new DatabaseSync(repo.file);
try {
db.prepare(`INSERT INTO image_requests
(account_id,project_id,output_id,variant_id,request_id,operation_id,slot_id,request_spec_hash,revision,state,prepared_json,receipt_json)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`).run(...repo.scope,draft.requestId,draft.operationId,draft.slotId,draft.requestSpecHash,
draft.revision,state,JSON.stringify(draft),receipt&&JSON.stringify(receipt));
} finally { db.close(); }
}
async function fixture(t) {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-project-repository-'));
t.after(() => cleanup(dir));
const file = path.join(dir, 'project-repository.sqlite');
const open = (overrides = {}) => new ProjectRepository(file, { ...scope, ...overrides });
return { dir, file, open, repo: open() };
}
async function asset(dir, assetId, bytes) {
const file = path.join(dir, assetId);
await fs.writeFile(file, bytes);
return { assetId, path: file, sha256: hash(bytes) };
}
test('initializes a standard WAL database with scoped tables and foreign keys', async t => {
const { file, repo } = await fixture(t);
assert.equal(repo.readLedger(), null);
const db = new DatabaseSync(file, { enableForeignKeyConstraints: true });
try {
assert.equal(db.prepare('PRAGMA journal_mode').get().journal_mode, 'wal');
assert.equal(db.prepare('PRAGMA user_version').get().user_version, 1);
assert.equal(db.prepare('PRAGMA foreign_keys').get().foreign_keys, 1);
assert.throws(() => db.prepare('INSERT INTO delivery_assets VALUES (?, ?, ?, ?, ?, ?, ?)')
.run(...Object.values(scope), 'missing', 0, 'missing'), /FOREIGN KEY/);
assert.deepEqual(db.prepare('PRAGMA foreign_key_check').all(), []);
} finally { db.close(); }
});
test('reopens the project ledger under a deeply nested Windows profile', async t => {
const { dir } = await fixture(t);
const projectDir = path.join(dir, 'profile', 'jiansun', 'accounts', 'a'.repeat(64), 'projects',
'35a93e64-4a06-456c-a2c9-0f5617cb3428', 'agent', 'a'.repeat(64), '35a93e64-4a06-456c-a2c9-0f5617cb3428');
const file = path.join(projectDir, 'project-repository.sqlite');
assert.ok(file.length > 260);
const legacy = path.join(projectDir, 'production-detail-oak.json');
const original = {
binding,
items: { front: { state: 'unknown', heldOriginalId: 'original-candidate' } },
};
await fs.mkdir(projectDir, { recursive: true });
await fs.writeFile(legacy, JSON.stringify(original));
assert.deepEqual(new ProjectRepository(file, scope).readLedger(legacy), original);
assert.deepEqual(new ProjectRepository(file, scope).readLedger(), original);
});
test('imports the original journal once, including unknown IDs, cross-slot links and old drafts', async t => {
const { dir } = await fixture(t);
const store = productionStore(dir, { scope: scope.accountId, project: scope.projectId });
const legacyFile = path.join(dir, 'production-detail-oak.json');
const original = {
binding, creationRevision: 7, pageCopy: { canvasText: [[12, '旧文案']] },
preparedRequests: { draft: { slotId: 'side', prompt: '旧的待审原文' } },
copyEvidence: { 12: { field: 'copy', text: '旧文案', sources: ['P01'], pictures: ['front', 'side'] } },
items: {
front: { state: 'unknown', heldOriginalId: 'old-candidate', heldOriginalProjectId: 'old-project',
pendingOperation: { operationId: 'old-operation' }, attempts: [{ candidateId: 'old-candidate', reworkOf: 'first' }] },
side: { state: 'applied', candidateId: 'archive', approvals: [{ candidateId: 'archive', decision: 'pass' }] },
},
};
await fs.writeFile(legacyFile, JSON.stringify(original));
const ledger = store.ledger('detail', 'oak');
assert.deepEqual(ledger.read(), original);
await ledger.publishAudit(original);
const view = JSON.parse(await fs.readFile(legacyFile, 'utf8'));
assert.deepEqual(view.copyEvidence, original.copyEvidence);
assert.deepEqual(view.items.side.approvals, original.items.side.approvals);
assert.deepEqual(view.items.front.pendingOperation, original.items.front.pendingOperation);
await fs.writeFile(legacyFile, 'invalid after migration');
assert.deepEqual(store.ledger('detail', 'oak').read(), original);
await fs.unlink(legacyFile);
assert.deepEqual(store.ledger('detail', 'oak').read(), original);
});
test('P01 local facts, document evidence and delivery reopen without a collaboration service', async t => {
const { dir, open, repo } = await fixture(t);
const facts = { material: '橡木', source: 'P01', confirmed: true };
const plan = { factsRevision: 'v1', output: 'detail', fields: ['cover'] };
repo.saveVersion('product_facts', 'product', 'v1', facts);
repo.saveVersion('plan', 'production', 'v1', plan);
repo.replaceLedger({ binding, items: { front: { candidateId: 'a', state: 'applied' } } });
repo.recordCandidate('front', 'a', 'adoption', { documentKey: 'detail-oak', revision: 9, operationId: 'place-a' });
const editable = await asset(dir, 'detail.pcraft', 'native document bytes');
const delivery = { generationId: 'generation-1', planRevision: 'v1', assets: [editable] };
repo.publishDelivery(delivery);
assert.deepEqual(open().readVersion('product_facts', 'product', 'v1'), facts);
assert.deepEqual(open().readVersion('plan', 'production', 'v1'), plan);
assert.equal(open().readLedger().items.front.candidateId, 'a');
assert.deepEqual(open().readDelivery(), delivery);
});
test('P02 reopens the exact complete prompt from a legacy request', async t => {
const { file, open, repo } = await fixture(t);
const draft = request('long', { prompt: '自然光与质感。\n'.repeat(300) + '末尾必需限制:只保留一件。\r\n' });
assert.ok(draft.spec.prompt.length > 2000);
seedLegacyRequest(repo, draft);
assert.equal(open().readVersion('prompt', 'long', 1).prompt, draft.spec.prompt);
assert.equal(open().readImageRequest('long').prepared.spec.prompt, draft.spec.prompt);
const db = new DatabaseSync(file, { readOnly:true });
try {
assert.equal(db.prepare("SELECT count(*) AS count FROM project_versions WHERE kind = 'prompt'").get().count, 0);
} finally {
db.close();
}
});
test('P03 dispatches a host-confirmed request once without a Pi request row', async t => {
const { dir } = await fixture(t);
const store = productionStore(dir, { scope: scope.accountId, project: scope.projectId });
const repo = store.ledger('detail', 'oak').repository;
const draft = {...request('frozen'),phase:'prepared',outputId:'detail',variantId:'oak',templateHash:'template'};
const slot={id:'front',fieldId:'cover',candidates:[]};
const calls=[];
const host={store,productionGoal:{outputId:'detail',variantId:'oak'},canvas:{
workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak',
template:{contentHash:'template'},totalSlots:1,slots:[slot]}),
detailCopyFields:async()=>({fields:[]}),delta:async()=>{},
async imageRequest(action,args,execution){
if(action==='pending')return [];
if(action==='read'||action==='prepare')return {...draft};
calls.push(args);
assert.equal(args.expectedRevision,draft.revision);
assert.equal(args.expectedHash,draft.requestSpecHash);
execution.onEnqueued();
draft.phase='complete';
slot.candidates.push({id:draft.requestId,status:'complete'});
return {status:'complete',id:draft.requestId};
},
}};
completeCanvas(host.canvas);
const tools=await openProductionOperations(host);
const prepared=await tools.prepare_image_request({slotId:'cover',prompt:draft.spec.prompt});
assert.equal((await tools.dispatch_image_request(approve(prepared))).phase,'accepted');
assert.equal((await tools.await_image_slots({})).generation[0].phase,'complete');
assert.equal((await tools.dispatch_image_request({requestId:prepared.requestId})).phase,'complete');
assert.deepEqual(calls,[{...approve(draft),slotId:'front',workerNumber:1}]);
assert.equal(repo.readImageRequest(draft.requestId),null);
assert.equal(repo.readLedger(),null);
await assert.rejects(fs.stat(path.join(dir,'production-detail-oak.json')),{code:'ENOENT'});
await tools.close();
});
test('P04 keeps original and normalized references, asset identities and send order', async t => {
const { dir, repo, open } = await fixture(t);
const original = await asset(dir, 'original.jpg', 'original');
const crop = await asset(dir, 'cropped.png', 'crop');
const wide = await asset(dir, 'wide.png', 'wide');
for (const input of [original, crop, wide]) repo.saveAsset(input);
const references = [crop, wide].map((input, index) => ({
position: index + 1, role: 'product', source: 'P1', originalAssetId: original.assetId,
sourceSha256: original.sha256, assetId: input.assetId, sha256: input.sha256,
}));
seedLegacyRequest(repo, request('p1', { prompt: '同款两视角。', references }));
assert.deepEqual(open().readImageRequest('p1').prepared.spec.references, references);
assert.equal(open().readAsset(references[0].originalAssetId).path, original.path);
assert.equal(open().readAsset(references[1].assetId).path, wide.path);
});
test('P05 a prompt edit cannot relabel a candidate generated by the old request', async t => {
const { repo } = await fixture(t);
const first = request('old', { prompt: '第一版' });
const corrected = { ...request('rework', { prompt: '新取景' }), reworkOf: 'old', reworkChange: '修改机位' };
seedLegacyRequest(repo, first);
seedLegacyRequest(repo, corrected);
repo.recordCandidate('front', 'old', 'candidate', { requestId: 'old', requestSpecHash: first.requestSpecHash });
repo.recordCandidate('side', 'reuse', 'candidate', { reusedFrom: { projectId: 'project', candidateId: 'old' } });
assert.equal(repo.candidateEvidence('front', 'old')[0].detail.requestSpecHash, first.requestSpecHash);
assert.equal(repo.readImageRequest('old').prepared.spec.prompt, '第一版');
assert.equal(repo.readImageRequest('rework').prepared.reworkOf, 'old');
assert.equal(repo.candidateEvidence('side', 'reuse')[0].detail.reusedFrom.candidateId, 'old');
});
test('P06 plans keep dynamic field bindings while shared material has one source identity', async t => {
const { repo } = await fixture(t);
const slots = [{ id: 'front', fieldId: 'cover' }, { id: 'side', fieldId: 'gallery' }, { id: 'joint', fieldId: 'join' }];
const { planRevision } = recordProductionInputs(repo, {
template: { contentHash: 'unrelated-to-D01' }, productVariantId: 'oak',
}, slots);
repo.recordCandidate('front', 'a', 'candidate', { materialTaskId: 'one-asset' });
repo.recordCandidate('side', 'b', 'candidate', { materialTaskId: 'one-asset' });
assert.deepEqual(repo.readVersion('plan', 'production', planRevision).slots, slots);
const materialIds = [['front','a'], ['side','b']].map(([slot, id]) => repo.candidateEvidence(slot, id)[0].detail.materialTaskId);
assert.equal(new Set(materialIds).size, 1);
});
test('P07 two intentionally equivalent samples keep distinct operations and actual reviews', async t => {
const { open, repo } = await fixture(t);
const a = request('sample-a');
const b = request('sample-b');
assert.equal(a.requestSpecHash, b.requestSpecHash);
for (const draft of [a, b]) {
seedLegacyRequest(repo, draft);
}
for (const draft of [a, b]) {
repo.recordCandidate(draft.slotId,draft.requestId,'review',{candidateId:draft.requestId,decision:'pass'});
}
assert.notEqual(open().readImageRequest(a.requestId).operationId, open().readImageRequest(b.requestId).operationId);
assert.deepEqual(repo.candidateEvidence('front', b.requestId).map(row => row.kind), ['review']);
});
test('P08 reads the original dispatching state from a historical database after reopening', async t => {
const {repo,open}=await fixture(t);
const draft=request();
seedLegacyRequest(repo,draft,'dispatching');
const saved=open().readImageRequest(draft.requestId);
assert.equal(saved.state,'dispatching');
assert.equal(saved.operationId,draft.operationId);
});
test('P09 output, variant, project and account are independent even when their IDs overlap', async t => {
const { repo, open } = await fixture(t);
const neighbors = [open({ variantId: 'walnut' }), open({ outputId: 'main_images' }),
open({ projectId: 'other' }), open({ accountId: 'other' })];
const draft = request();
seedLegacyRequest(repo, draft);
for (const other of neighbors) {
assert.equal(other.readImageRequest(draft.requestId), null);
assert.equal(other.readLedger(), null);
other.replaceLedger({ binding: 'independent', items: { front: { candidateId: 'other' } } });
}
repo.updateLedger(binding, journal => { journal.items.front = {candidateId:draft.requestId}; });
for (const other of neighbors) assert.equal(other.readLedger().items.front.candidateId, 'other');
});
test('P10 retirement preserves review evidence and leaves independent referenced files alone', async t => {
const { dir, repo } = await fixture(t);
const rejected = await asset(dir, 'rejected.png', 'wrong structure');
const accepted = await asset(dir, 'accepted.png', 'same product');
repo.recordCandidate('front', 'rejected', 'review', { reason: '扶手结构错误', sha256: rejected.sha256 });
repo.saveAsset(accepted);
repo.replaceLedger({ binding, items: { front: { candidateId: 'rejected' }, side: { candidateId: 'accepted' } } });
await fs.unlink(rejected.path);
repo.updateLedger(binding, journal => { journal.items.front = { state: 'retired' }; }, {
evidence: ['front', 'rejected', 'retirement', { sha256: rejected.sha256, bytesRemoved: true }],
});
assert.equal(repo.readLedger().items.side.candidateId, 'accepted');
assert.equal(repo.candidateEvidence('front', 'rejected')[0].detail.reason, '扶手结构错误');
assert.equal(repo.candidateEvidence('front', 'rejected')[1].detail.bytesRemoved, true);
assert.equal(await fs.readFile(repo.readAsset(accepted.assetId).path, 'utf8'), 'same product');
});
test('P11 records the actual background request separately from local compositing', async t => {
const { repo } = await fixture(t);
const draft = request('background', { prompt: '移除模板中的旧商品。', sceneComposite: true,
references: [{ position: 1, role: 'scene', sha256: hash('template scene') }] });
seedLegacyRequest(repo,draft,'complete',{status:'complete'});
repo.recordCandidate('front', 'composite', 'candidate', { requestId: 'background',
processing: { kind: 'composite', productAssetId: 'actual-product-cutout', placement: [10, 20, 900, 1200] } });
assert.deepEqual(repo.readImageRequest('background').prepared.spec.references.map(row => row.role), ['scene']);
assert.equal(repo.candidateEvidence('front', 'composite')[0].detail.processing.productAssetId, 'actual-product-cutout');
});
test('P12 keeps an in-session placement pending until a durable document receipt arrives', async t => {
const { open, repo } = await fixture(t);
const prepared = { candidateId: 'a', operationId: 'place', run: 'previous-run', documentId: 5 };
repo.replaceLedger({ binding, items: { front: { pendingAdoption: prepared } } });
repo.recordCandidate('front', 'a', 'adoption', { ...prepared, phase: 'complete', persistence: 'session' });
assert.deepEqual(open().readLedger().items.front.pendingAdoption, prepared);
open().updateLedger(binding, journal => { journal.items.front.pendingAdoption = null; },
{ evidence: ['front', 'a', 'adoption', { ...prepared, phase: 'complete', persistence: 'verified', documentRevision: 8 }] });
assert.equal(repo.candidateEvidence('front', 'a').at(-1).detail.documentRevision, 8);
assert.equal(repo.readLedger().items.front.pendingAdoption, null);
});
test('P13 reloads full facts, plan, formal prompt and locked rule from stable versions', async t => {
const { open, repo } = await fixture(t);
const { productFactsRevision, planRevision } = recordProductionInputs(repo, {
productEvidence: { brief: { name: '餐桌', variants: [{ id: 'oak', colorName: '橡木' }] },
facts: { items: [{ id: 'F01', value: '圆角', source: 'P1' }] } },
productVariantId: 'oak', revisions: { creation: 5 }, template: { contentHash: 'template' },
}, [{ id: 'front', fieldId: 'cover', requirements: '展示圆角' }]);
const draft = { ...request(), productFactsRevision, planRevision,
knowledge: [{ fileId: 'image-prompt', revision: 'r7' }] };
seedLegacyRequest(repo, draft);
const { prepared } = open().readImageRequest(draft.requestId);
assert.equal(open().readVersion('product_facts', 'product', prepared.productFactsRevision).facts.items[0].source, 'P1');
assert.equal(open().readVersion('plan', 'production', prepared.planRevision).slots[0].requirements, '展示圆角');
assert.equal(prepared.spec.prompt, draft.spec.prompt);
assert.deepEqual(prepared.knowledge, draft.knowledge);
});
test('production facts retain only this variant barcodes without mixing different barcode values', async t => {
const { repo, open } = await fixture(t);
const brief = {
name: '餐桌',
variants: [{ id: 'oak', colorName: '橡木' }, { id: 'white', colorName: '白色' }],
barcodeBindings: { oak: '00123456\n00123457', white: '00999999' },
intake: {
templateId: 'table',
schema: { fields: [{ id: 'width', label: '宽度', scope: 'barcode' }] },
productValues: { material: '木' },
barcodeValues: {
'00123456': { width: '120 cm' },
'00123457': { width: '140 cm' },
'00999999': { width: '160 cm' },
},
},
};
const { productFactsRevision } = recordProductionInputs(repo, {
productEvidence: { brief, facts: {} },
productVariantId: 'oak', revisions: { creation: 1 }, template: {},
}, []);
const saved = open().readVersion('product_facts', 'product', productFactsRevision);
assert.deepEqual(saved.brief.barcodes, ['00123456', '00123457']);
assert.deepEqual(saved.brief.intake.barcodeValues, {
'00123456': { width: '120 cm' },
'00123457': { width: '140 cm' },
});
assert.equal(saved.brief.intake.productValues.material, '木');
assert.equal(saved.variant.id, 'oak');
assert.equal(saved.brief.barcodeBindings, undefined);
});
test('P15 execution success and a failed pixel check remain independently traceable', async t => {
const { open, repo } = await fixture(t);
const draft = request('undersize', { prompt: '输出 4K,保留产品结构。' });
seedLegacyRequest(repo,draft,'complete',{status:'complete'});
repo.recordCandidate('front', draft.requestId, 'review', {
decision: 'revise', actualPixels: [1024, 1024], reason: '尺寸不足且接合结构错误',
});
const next = { ...request('corrected'), reworkOf: draft.requestId };
seedLegacyRequest(repo, next);
assert.equal(open().readImageRequest(draft.requestId).prepared.spec.prompt,draft.spec.prompt);
assert.equal(open().candidateEvidence('front', draft.requestId)[0].detail.decision, 'revise');
assert.equal(open().readImageRequest(next.requestId).prepared.reworkOf, draft.requestId);
});
test('delivery publication is atomic and large files stay outside SQLite', async t => {
const { dir, file, open, repo } = await fixture(t);
const bytes = Buffer.alloc(4 * 1024 * 1024, 42);
const editable = await asset(dir, 'large.pcraft', bytes);
const original = { generationId: 'original', assets: [editable] };
repo.publishDelivery(original);
assert.throws(() => repo.publishDelivery({ generationId: 'incomplete', assets: [
{ ...editable, assetId: 'rollback' }, { ...editable, sha256: hash('wrong input') },
] }), /资产记录已变化/);
assert.equal(open().readDelivery('incomplete'), null);
assert.equal(open().readAsset('rollback'), null);
assert.deepEqual(open().readDelivery(), original);
const next = await asset(dir, 'next.jpg', 'new-generation');
repo.publishDelivery({ generationId: 'next', assets: [next] });
repo.publishDelivery(original);
assert.equal(open().readDelivery().generationId, 'next');
assert.deepEqual(open().readDelivery('original'), original);
assert.throws(() => repo.saveAsset({ ...editable, assetId: 'bad', bytes }), /只接受资产路径和哈希/);
assert.throws(() => repo.saveVersion('plan', 'binary-image', '1', {
image: { type: 'image', data: 'hidden-bytes' },
}), /只接受资产路径和哈希/);
assert.ok((await fs.stat(file)).size < bytes.length / 20);
assert.equal(hash(await fs.readFile(editable.path)), editable.sha256);
});