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

376 lines
22 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 { Worker } from 'node:worker_threads';
import { openProductionOperations } from '../src/production-operations.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,
});
const pending = journal => journal.items.front?.pendingOperation;
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('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 stores the exact complete prompt and rejects changes at the same revision', async t => {
const { open, repo } = await fixture(t);
const draft = request('long', { prompt: '自然光与质感。\n'.repeat(300) + '末尾必需限制:只保留一件。\r\n' });
assert.ok(draft.spec.prompt.length > 2000);
repo.saveImageRequest(draft);
assert.equal(open().readVersion('prompt', 'long', 1).prompt, draft.spec.prompt);
assert.equal(open().readImageRequest('long').prepared.spec.prompt, draft.spec.prompt);
assert.throws(() => repo.saveImageRequest(request('long', { prompt: 'changed' })), /新版本/);
});
test('P03 the production bridge sends only the reviewed identity after an atomic local freeze', 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', { prompt: '原始完整文字\n保留边缘', modelId: 'actual-model',
parameters: { size: '2048x2048' }, references: [{ position: 1, role: 'product', sha256: hash('reference') }] });
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: [{ id: 'front', fieldId: 'cover' }] }),
detailCopyFields: async () => ({ fields: [] }),
delta: async () => {},
async imageRequest(action, args) {
if (action === 'prepare') return draft;
calls.push(args);
const saved = repo.readImageRequest(draft.requestId);
assert.equal(saved.state, 'dispatching');
assert.equal(typeof saved.frozenAt, 'number');
assert.deepEqual(saved.prepared.spec, draft.spec);
assert.equal(repo.readLedger().items.front.pendingGenerations[draft.requestId].operationId, draft.operationId);
const portable = JSON.parse(await fs.readFile(path.join(dir, 'production-detail-oak.json'), 'utf8'));
assert.equal(portable.items.front.pendingGenerations[draft.requestId].operationId, draft.operationId);
assert.equal(portable.preparedRequests[draft.requestId].prompt, draft.spec.prompt);
return { status: 'complete', id: draft.requestId, materialTaskId: draft.requestId };
},
}};
const tools = await openProductionOperations(host);
const prepared = await tools.prepare_image_request({ slotId: 'cover', prompt: draft.spec.prompt });
await tools.dispatch_image_request({ ...approve(prepared), expectedRevision: 2 });
assert.equal((await tools.await_image_slots({ slotIds: ['cover'] })).generation[0].phase, 'failed');
assert.equal(calls.length, 0);
for (let attempt = 0; attempt < 2; attempt++) {
await tools.dispatch_image_request(approve(prepared));
assert.equal((await tools.await_image_slots({ slotIds: ['cover'] })).generation[0].phase, 'complete');
}
assert.deepEqual(calls, [{ ...approve(draft), slotId: 'front' }]);
assert.equal(repo.readImageRequest(draft.requestId).receipt.status, 'complete');
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,
}));
repo.saveImageRequest(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: '修改机位' };
repo.saveImageRequest(first);
repo.saveImageRequest(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]) {
repo.saveImageRequest(draft);
assert.equal(repo.claimImageRequest(approve(draft), binding, pending).claimed, true);
}
assert.deepEqual(Object.keys(open().readLedger().items.front.pendingGenerations), [a.requestId, b.requestId]);
for (const draft of [a, b]) {
repo.updateLedger(binding, journal => { delete journal.items[draft.slotId].pendingGenerations[draft.requestId]; }, {
receipt: [draft.requestId, 'complete', { status: 'complete' }],
evidence: [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 concurrent workers claim one operation and a restarted worker retains the original', async t => {
const { file, open, repo } = await fixture(t);
const draft = request('interrupted');
repo.saveImageRequest(draft);
const start = new SharedArrayBuffer(4);
const run = () => new Promise((resolve, reject) => {
const worker = new Worker(`
const { parentPort, workerData } = require('node:worker_threads');
(async () => {
const { ProjectRepository } = await import(workerData.module);
const repo = new ProjectRepository(workerData.file, workerData.scope);
const barrier = new Int32Array(workerData.start);
Atomics.add(barrier, 0, 1);
Atomics.notify(barrier, 0);
Atomics.wait(barrier, 0, 1, 5000);
parentPort.postMessage(repo.claimImageRequest(workerData.approval, workerData.binding,
journal => journal.items.front?.pendingOperation).claimed);
})().catch(error => { throw error; });
`, { eval: true, workerData: { start, file, scope, binding, approval: approve(draft),
module: new URL('../src/project-repository.mjs', import.meta.url).href } });
worker.once('message', resolve);
worker.once('error', reject);
});
assert.deepEqual((await Promise.all([run(), run()])).sort(), [false, true]);
const resumed = open().claimImageRequest(approve(draft), binding, pending);
assert.equal(resumed.claimed, false);
assert.equal(resumed.pending.operationId, draft.operationId);
assert.equal(open().readImageRequest(draft.requestId).state, 'dispatching');
});
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();
repo.saveImageRequest(draft);
repo.claimImageRequest(approve(draft), binding, pending);
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; },
{ receipt: [draft.requestId, 'complete', { status: 'complete' }] });
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') }] });
repo.saveImageRequest(draft);
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' }] };
repo.saveImageRequest(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('P14 reads the locked rule on demand and surfaces an unavailable reference', async t => {
const { dir } = await fixture(t);
const store = productionStore(dir);
let available = false;
const tools = await openProductionOperations({ store, productionGoal: { outputId: 'detail', variantId: 'oak' },
canvas: { workflowRead: async () => ({ available: true, canvasFirst: true, outputId: 'detail', productVariantId: 'oak',
template: { contentHash: 'template' }, totalSlots: 0, slots: [] }) },
productionSkills: { knowledge: { rules: [{ fileId: 'prompt-framework', revision: 'locked', kind: 'image-prompt',
loadText: async () => {
if (!available) throw Error('锁定版本引用暂不可读取');
return '正式提示词结构';
} }] } },
});
await assert.rejects(tools.read_production_knowledge({ fileId: 'prompt-framework' }), /锁定版本引用暂不可读取/);
available = true;
const rule = await tools.read_production_knowledge({ fileId: 'prompt-framework' });
assert.deepEqual(rule, { fileId: 'prompt-framework', revision: 'locked', text: '正式提示词结构', nextOffset: null });
});
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,保留产品结构。' });
repo.saveImageRequest(draft);
repo.claimImageRequest(approve(draft), binding, pending);
repo.recordImageReceipt(draft.requestId, 'complete', { status: 'complete' });
repo.recordCandidate('front', draft.requestId, 'review', {
decision: 'revise', actualPixels: [1024, 1024], reason: '尺寸不足且接合结构错误',
});
const next = { ...request('corrected'), reworkOf: draft.requestId };
repo.saveImageRequest(next);
assert.equal(open().readImageRequest(draft.requestId).state, 'complete');
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);
});