From fe533072b4467ad81e2d2bc57c4de12c770e1b74 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Thu, 3 Dec 2026 23:59:26 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BB=9F=E4=B8=80=E6=99=BA=E8=83=BD=E4=BD=93?= =?UTF-8?q?=E5=95=86=E5=93=81=E6=A1=A3=E6=A1=88=E8=AF=BB=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/detail-agent-pi/src/product-brief.mjs | 282 +++++++++++++++--- apps/detail-agent-pi/src/production-copy.mjs | 39 +++ apps/detail-agent-pi/src/production-goal.mjs | 11 +- .../src/production-operations.mjs | 46 +-- .../src/production-repository.mjs | 52 ++-- .../src/production-screen-tools.mjs | 6 +- apps/detail-agent-pi/src/project-context.mjs | 57 ++-- .../test/product-brief.test.mjs | 119 +++++++- .../test/production-goal.test.mjs | 28 ++ .../test/production-operations.test.mjs | 66 +++- 10 files changed, 559 insertions(+), 147 deletions(-) diff --git a/apps/detail-agent-pi/src/product-brief.mjs b/apps/detail-agent-pi/src/product-brief.mjs index 7b891435..8aab7270 100644 --- a/apps/detail-agent-pi/src/product-brief.mjs +++ b/apps/detail-agent-pi/src/product-brief.mjs @@ -7,53 +7,261 @@ export function splitBarcodes(input) { export function projectSpu(brief) { const source = brief ?? {}; - return (source.identifierType === 'spu' ? source.identifier : source.deliverySpu)?.trim() - || source.normalizedProduct?.identity?.spu?.trim() || undefined; + const legacy = fieldText(source.identifierType === 'spu' ? source.identifier : source.deliverySpu).trim() + || fieldText(source.normalizedProduct?.identity?.spu).trim() || fieldText(source.platformFacts?.spu).trim(); + return fieldText(source.spu ?? legacy).trim() || undefined; } -export function briefVariants(brief) { - return Array.isArray(brief?.variants) ? brief.variants - : Array.isArray(brief?.normalizedProduct?.variants) ? brief.normalizedProduct.variants : []; -} +const list = value => Array.isArray(value) ? value : []; +const record = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}; +const fieldText = value => typeof value === 'string' || typeof value === 'number' ? String(value) : ''; +const axes = ['length', 'width', 'height']; +const units = new Map([['mm', 'mm'], ['毫米', 'mm'], ['cm', 'cm'], ['厘米', 'cm'], ['m', 'm'], ['米', 'm']]); +const unitScale = new Map([['mm', 1], ['cm', 10], ['m', 1000]]); +const dimensionUnit = value => units.get(fieldText(value).trim().toLowerCase()) ?? fieldText(value).trim(); +const materialKeys = ['material', 'materialtype', '材质', '材质类型']; +const boardKeys = ['boardtype', '板材类型', '板材']; -export function briefBarcodeBindings(brief) { - if (brief?.barcodeBindings) return brief.barcodeBindings; - const variants = brief?.normalizedProduct?.variants; - if (!Array.isArray(variants)) return undefined; - return Object.fromEntries(variants.map(({ id, barcodes }) => - [id, Array.isArray(barcodes) ? barcodes.map(row => row.barcode) : []])); -} - -export function normalizedProductEvidence(product, scope) { - if (!product?.identity) return undefined; - const { identity, specs, copy } = product; - const variants = Array.isArray(product.variants) ? product.variants : []; - const assets = Array.isArray(product.assets) ? product.assets : []; - const scopedVariants = scope ? variants.filter(row => row.id === scope.variantId).map(row => ({ - ...row, - barcodes: (Array.isArray(row.barcodes) ? row.barcodes : []).filter(entry => scope.barcodes.includes(entry.barcode)), - })) : variants; - const imageIds = new Set(scopedVariants.flatMap(row => Array.isArray(row.barcodes) - ? row.barcodes.flatMap(entry => entry.imageIds ?? []) : [])); - return { identity, specs, copy, variants: scopedVariants, - assets: assets.filter(asset => !scope || !asset.barcode || scope.barcodes.includes(asset.barcode) || imageIds.has(asset.id)) - .map(({ id, kind, label, barcode, colorName, selectedForProject }) => - ({ id, kind, label, barcode, colorName, selectedForProject })), +function barcodeEntry(barcode, { colorName, dimensions, material, boardType }) { + return { + barcode, colorName: fieldText(colorName), + dimensions: { length: fieldText(dimensions?.length), width: fieldText(dimensions?.width), + height: fieldText(dimensions?.height), unit: dimensionUnit(dimensions?.unit) }, + material: fieldText(material), boardType: fieldText(boardType), }; } -export function detailBarcode(brief) { +function barcodeOwners(brief) { + const owners = new Map(); + for (const variant of list(brief?.normalizedProduct?.variants)) { + for (const row of list(variant.barcodes)) owners.set(row.barcode?.trim(), variant.id); + } + for (const [owner, binding] of Object.entries(record(brief?.barcodeBindings))) { + for (const barcode of splitBarcodes(binding)) owners.set(barcode, owner); + } + for (const row of list(brief?.barcodeEntries)) { + if (row?.variantId) owners.set(row.barcode?.trim(), row.variantId); + } + return owners; +} + +function legacyDimensions(sources, values, fields, fallbackUnit) { + const answers = new Map(fields.map(field => [field.id ?? field.key, field.unit])); + const hasAxes = row => axes.some(axis => fieldText(row?.[axis])); + const sourceUnit = sources.find(row => row?.unit)?.unit ?? fallbackUnit; + const unit = dimensionUnit(sources.find(row => row?.unit && hasAxes(row))?.unit) + || dimensionUnit(axes.map(axis => fieldText(values[axis]) && answers.get(axis)).find(Boolean)) + || (hasAxes(values) || sources.some(hasAxes) ? dimensionUnit(sourceUnit) : ''); + const dimensions = { unit }; + const to = unitScale.get(unit); + for (const axis of axes) { + const source = sources.find(row => fieldText(row?.[axis])); + const answer = fieldText(values[axis]); + const value = answer || fieldText(source?.[axis]); + const from = unitScale.get(dimensionUnit(answer ? answers.get(axis) || sourceUnit : source?.unit)); + dimensions[axis] = value && from && to && from !== to && Number.isFinite(Number(value)) + ? String(Number((Number(value) * (from / to)).toPrecision(15))) : value; + } + return dimensions; +} + +function legacyAttribute(row, keys) { + const attributes = row?.attributes; + return (Array.isArray(attributes) ? attributes.map(({ key, value }) => [key, value]) : Object.entries(record(attributes))) + .find(([key, value]) => keys.includes(key.replace(/[_\s-]/gu, '').toLowerCase()) && fieldText(value))?.[1]; +} + +export function briefBarcodeEntries(brief = {}) { + const entries = new Map(); + if (Array.isArray(brief.barcodeEntries)) { + for (const row of brief.barcodeEntries) { + const barcode = fieldText(row?.barcode).trim(); + if (barcode && !entries.has(barcode)) entries.set(barcode, barcodeEntry(barcode, row)); + } + return [...entries.values()]; + } + + const normalized = brief.normalizedProduct; + const platform = record(brief.platformFacts?.barcodes); + const intake = record(brief.intake?.barcodeValues); + const imported = new Map(); + for (const variant of list(normalized?.variants)) { + for (const row of list(variant.barcodes)) { + const barcode = fieldText(row.barcode).trim(); + if (barcode && !imported.has(barcode)) imported.set(barcode, { row, variant }); + } + } + const owners = barcodeOwners(brief); + const barcodes = splitBarcodes([ + ...Object.values(record(brief.barcodeBindings)).flatMap(splitBarcodes), ...imported.keys(), + ...Object.keys(platform), ...Object.keys(intake), ...list(brief.barcodes).map(row => row?.barcode ?? row), + ...(brief.identifierType === 'barcode' ? [brief.identifier] : []), + ]); + const legacyRows = new Map(list(brief.barcodes).filter(row => row?.barcode).map(row => [row.barcode.trim(), row])); + const variants = briefVariants(brief); + const shared = brief.platformFacts?.shared; + const intakeFields = list(brief.intake?.schema?.barcodeFields); + return barcodes.map(barcode => { + const { row, variant } = imported.get(barcode) ?? {}; + const facts = Object.hasOwn(platform, barcode) ? platform[barcode] : undefined; + const answers = Object.hasOwn(intake, barcode) ? record(intake[barcode]) : {}; + const legacy = legacyRows.get(barcode); + const owner = variants.find(item => item.id === owners.get(barcode)) ?? (variants.length === 1 ? variants[0] : undefined); + const dimensions = [row?.dimensions, facts?.dimensions, legacy?.dimensions]; + if (barcodes.length === 1 || barcode === brief.detailBarcode?.trim()) { + dimensions.push(brief.dimensions, normalized?.specs?.dimensions, shared?.dimensions); + } + return barcodeEntry(barcode, { + colorName: answers.colorName ?? (row?.colorName || facts?.colorName || legacy?.colorName + || owner?.colorName || variant?.colorName || brief.colorName), + dimensions: legacyDimensions(dimensions, answers, intakeFields, brief.dimensions?.unit), + material: answers.material ?? (row?.material || facts?.material || legacy?.material + || legacyAttribute(row, materialKeys) || legacyAttribute(facts, materialKeys) || owner?.materialName + || shared?.material || list(normalized?.specs?.materials).join('、')), + boardType: answers.boardType ?? (row?.boardType || facts?.boardType || legacy?.boardType + || legacyAttribute(row, boardKeys) || legacyAttribute(facts, boardKeys) || shared?.boardType + || legacyAttribute(shared, boardKeys) || legacyAttribute(normalized?.specs, boardKeys)), + }); + }); +} + +export function briefVariants(brief) { + const variants = Array.isArray(brief?.variants) ? brief.variants : list(brief?.normalizedProduct?.variants); + const byId = new Map(variants.filter(Boolean).map(row => [row.id, row])); + for (const { variantId, colorName } of list(brief?.barcodeEntries).filter(Boolean)) { + if (variantId && !byId.has(variantId)) byId.set(variantId, { id: variantId, colorName }); + } + return [...byId.values()]; +} + +export function briefBarcodeBindings(brief, entries = briefBarcodeEntries(brief)) { + const variants = briefVariants(brief); + const owners = barcodeOwners(brief); + const groups = Map.groupBy(entries, ({ barcode, colorName }) => { + const owner = owners.get(barcode); + return (owner !== 'default' && owner) || variants.find(row => colorName && row.colorName === colorName)?.id + || (variants.length === 1 ? variants[0].id : 'default'); + }); + return Object.fromEntries([...groups].map(([id, rows]) => [id, rows.map(row => row.barcode)])); +} + +function imageIdsForBarcodes(brief, barcodes) { + const rows = [...list(brief.barcodeEntries), ...list(brief.normalizedProduct?.variants).flatMap(row => list(row.barcodes))]; + return new Set(rows.filter(row => barcodes.includes(row?.barcode?.trim())).flatMap(row => list(row.imageIds))); +} + +const originNames = new Map([['upload', 'manual'], ['产品平台', 'product_platform']]); +const imagePurpose = new Map([['main', 'scene'], ['whiteBackground', 'product'], ['sku', 'product'], ['reference', 'scene']]); +const imageSource = image => image.source ?? image.localSource ?? image.ref ?? image.url; +const imageHash = source => /^(?:local|sha256):([a-f0-9]{64})$/i.exec(source)?.[1]?.toLowerCase(); +const imageIdentity = image => imageHash(imageSource(image)) ?? imageSource(image) ?? image.localPath; + +function briefImages(brief, scope) { + const assets = list(brief.normalizedProduct?.assets).filter(Boolean); + const images = [...list(brief.images), ...list(brief.barcodeEntries).flatMap(row => + row?.barcode ? list(row.images).map(image => ({ ...image, barcode: image.barcode ?? row.barcode })) : []), + ...briefVariants(brief).flatMap(row => list(row.images).map(image => ({ ...image, variantId: row.id })))].filter(Boolean); + const disabled = new Set([...images, ...assets].filter(image => image.selectedForProject === false || image.selected === false) + .map(image => image.assetId ?? image.id).filter(Boolean)); + const byAsset = new Map(assets.map(asset => [asset.id, asset])); + const bySource = new Map(assets.filter(imageIdentity).map(asset => [imageIdentity(asset), asset])); + const linkedAssets = new Set(images.map(image => image.assetId ?? image.id ?? bySource.get(imageIdentity(image))?.id)); + const selected = new Map(); + const imageIds = scope && imageIdsForBarcodes(brief, scope.barcodes); + for (const image of [...images, ...assets.filter(asset => !linkedAssets.has(asset.id))]) { + const asset = byAsset.get(image.assetId ?? image.id) ?? bySource.get(imageIdentity(image)); + const id = image.id ?? image.assetId ?? asset?.id; + if (image.selected === false || image.selectedForProject === false || disabled.has(asset?.id ?? id)) continue; + const { kind, label } = { ...asset, ...image }; + const barcode = image.barcode === undefined ? asset?.barcode : image.barcode; + const variantId = image.variantId; + if (scope && ((variantId && variantId !== scope.variantId) + || (barcode && !scope.barcodes.includes(barcode) && !imageIds.has(asset?.id ?? id)))) continue; + const source = imageSource(image) ?? (asset && imageSource(asset)); + const origin = image.origin ?? asset?.origin ?? (asset || image.platformImage ? 'product_platform' : undefined); + const localPath = image.localPath ?? asset?.localPath; + const row = { id, source, localPath, name: image.name ?? label, purpose: image.purpose ?? imagePurpose.get(kind), + barcode: barcode || undefined, origin: originNames.get(origin) ?? origin, selected: true, + scope: barcode ? 'barcode' : variantId ? 'variant' : 'common', variantId, kind, label, + assetId: image.assetId, imageRole: image.imageRole, fieldKey: image.fieldKey, templateId: image.templateId, + description: image.description, ref: image.ref }; + const imageKey = asset?.id ?? imageIdentity(row) ?? id; + const key = imageKey ? JSON.stringify([imageKey, row.barcode, variantId, row.fieldKey, row.purpose]) : row; + const fields = Object.fromEntries(Object.entries(row).filter(([, value]) => value != null)); + selected.set(key, { ...fields, ...selected.get(key) }); + } + return [...selected.values()]; +} + +export function canonicalProductBrief(brief = {}, scope, entries = briefBarcodeEntries(brief)) { + const identity = brief.normalizedProduct?.identity; + const persisted = Array.isArray(brief.barcodeEntries); + const name = persisted ? brief.name ?? identity?.productName : brief.name || identity?.productName; + const brand = persisted ? brief.brandName ?? identity?.platformBrand : brief.brandName || identity?.platformBrand; + const category = persisted ? brief.categoryName ?? identity?.platformCategory : brief.categoryName || identity?.platformCategory; + const intake = record(brief.intake); + const barcodeValues = record(intake.barcodeValues); + return { + name: fieldText(name), spu: projectSpu(brief) ?? '', + brand: fieldText(brief.brand ?? brand), category: fieldText(brief.category ?? category), + note: fieldText(brief.note), + barcodeEntries: scope ? entries.filter(row => scope.barcodes.includes(row.barcode)) : entries, + images: briefImages(brief, scope), + intake: { ...intake, productValues: record(intake.productValues), barcodeValues: scope + ? Object.fromEntries(scope.barcodes.filter(code => Object.hasOwn(barcodeValues, code)).map(code => [code, barcodeValues[code]])) + : barcodeValues }, + }; +} + +export function productImageEvidence({ source, localPath, ref, ...image }) { + const hash = imageHash(ref) ?? imageHash(source); + for (const key of ['name', 'label', 'description']) { + if (/(?:https?:\/\/|data:|[\\/]|[a-z]:)/i.test(image[key])) delete image[key]; + } + return { ...image, ...(hash ? { ref: `sha256:${hash}`, source: `local:${hash}` } : {}) }; +} + +export function legacyProductEvidence(brief, images, scope) { + // The saved legacy signature also included assets that have since been excluded from the agent view. + if (images && Array.isArray(brief.barcodeEntries)) return {}; + const product = brief.normalizedProduct; + if (product?.identity) { + const { identity, specs, copy } = product; + const variants = list(product.variants); + const imageIds = images ? new Set(images.map(image => image.assetId ?? image.id)) + : new Set(variants.filter(row => row.id === scope?.variantId).flatMap(row => list(row.barcodes) + .filter(entry => scope.barcodes.includes(entry.barcode)).flatMap(entry => list(entry.imageIds)))); + return { normalizedProduct: { identity, specs, copy, + variants: scope ? variants.filter(row => row.id === scope.variantId).map(row => ({ + ...row, barcodes: list(row.barcodes).filter(entry => scope.barcodes.includes(entry.barcode)), + })) : variants, + assets: list(product.assets).filter(asset => imageIds.has(asset.id) + || (!images && (!scope || !asset.barcode || scope.barcodes.includes(asset.barcode)))) + .map(({ id, kind, label, barcode, colorName, selectedForProject }) => + ({ id, kind, label, barcode, colorName, selectedForProject })), + } }; + } + if (!brief.platformFacts) return {}; + const { shared, barcodes } = brief.platformFacts; + return { platformFacts: scope ? { shared, barcodes: Object.fromEntries(scope.barcodes + .filter(code => Object.hasOwn(record(barcodes), code)).map(code => [code, barcodes[code]])) } : brief.platformFacts }; +} + +export function detailBarcode(brief, entries = briefBarcodeEntries(brief)) { const source = brief ?? {}; - const bindings = briefBarcodeBindings(source) ?? {}; - const barcodes = new Set(Object.values(bindings).flatMap(splitBarcodes)); - const selected = source.detailBarcode?.trim() ?? (barcodes.size === 1 ? barcodes.values().next().value : undefined); - if (selected !== undefined && !barcodes.has(selected)) { + const selected = source.detailBarcode?.trim() || (entries.length === 1 ? entries[0].barcode : undefined); + if (selected !== undefined && !entries.some(row => row.barcode === selected)) { throw Error('详情主条码必须属于当前项目'); } return selected; } -export function variantBarcodes(brief, variantId) { - const bindings = briefBarcodeBindings(brief); - return splitBarcodes(bindings?.[variantId] ?? (briefVariants(brief).length <= 1 ? bindings?.default : undefined)); +export function variantBarcodes(brief, variantId, bindings = briefBarcodeBindings(brief)) { + return Object.hasOwn(bindings, variantId) ? bindings[variantId] + : briefVariants(brief).length <= 1 && Object.hasOwn(bindings, 'default') ? bindings.default : []; +} + +export function variantColorName(variant, entries) { + if (!entries.length) return variant?.colorName; + return entries.every(row => row.colorName === entries[0].colorName) ? entries[0].colorName : undefined; } diff --git a/apps/detail-agent-pi/src/production-copy.mjs b/apps/detail-agent-pi/src/production-copy.mjs index fe9ebdba..53c6e134 100644 --- a/apps/detail-agent-pi/src/production-copy.mjs +++ b/apps/detail-agent-pi/src/production-copy.mjs @@ -1,4 +1,43 @@ import { scopedProductionBrief } from './production-repository.mjs'; +import { legacyProductEvidence, splitBarcodes } from './product-brief.mjs'; + +// Older ledgers store the serialized inputs. Rebuild that view only when +// matching saved receipts, so a format upgrade does not discard copy decisions. +function legacyProductionInputs(plan, variantId, source, scopedCodes) { + const { variants, intake, barcodeBindings, detailBarcode, deliverySpu, normalizedProduct, platformFacts, ...brief } = source; + const normalizedVariants = normalizedProduct?.variants; + const bindings = barcodeBindings ?? (Array.isArray(normalizedVariants) ? Object.fromEntries(normalizedVariants + .map(({id,barcodes})=>[id,barcodes?.map(row=>row.barcode)??[]])) : undefined); + const rows = Array.isArray(variants) ? variants : normalizedVariants ?? []; + const matched = rows.find(row => row.id === variantId); + const variant = Array.isArray(variants) || !matched ? matched : { id: matched.id, colorName: matched.colorName }; + const spu = (source.identifierType === 'spu' ? source.identifier : deliverySpu)?.trim() || normalizedProduct?.identity?.spu?.trim(); + if (spu) brief.spu = spu; + const codes = [...new Set(Object.values(bindings ?? {}).flatMap(splitBarcodes))]; + const selected = plan.outputId === 'detail' ? detailBarcode?.trim() ?? (codes.length === 1 ? codes[0] : undefined) : undefined; + const barcodes = selected ? [selected] : splitBarcodes(bindings?.[variantId] ?? (rows.length <= 1 ? bindings?.default : undefined)); + if (barcodes.length !== scopedCodes.length || barcodes.some((code, index) => code !== scopedCodes[index])) return undefined; + if (selected) brief.detailBarcode = selected; + if (bindings) brief.barcodes = barcodes; + const legacy = legacyProductEvidence(source, undefined, { variantId, barcodes }); + const assetIds = new Set(legacy.normalizedProduct?.assets.map(asset => asset.id)); + if (Array.isArray(brief.images)) brief.images = brief.images.filter(image => + !image.barcode || barcodes.includes(image.barcode) || assetIds.has(image.assetId)); + Object.assign(brief, legacy); + if (intake) { + const values = intake.barcodeValues ?? {}; + brief.intake = { ...intake, barcodeValues: Object.fromEntries(barcodes + .filter(code => Object.hasOwn(values, code)).map(code => [code, values[code]])) }; + } + return JSON.stringify([brief, variant, (variants?.length ?? 0) > 1, plan.productEvidence.sellingPoints?.selected]); +} + +export function matchesProductionInputs(plan, variantId, saved, current = productionInputs(plan, variantId)) { + if (saved === current) return true; + const source = plan.productEvidence?.brief; + return typeof saved === 'string' && Boolean(source + && saved === legacyProductionInputs(plan, variantId, source, JSON.parse(current)[0].barcodes)); +} export function productionInputs(plan,variantId){ const brief=plan.productEvidence?.brief; diff --git a/apps/detail-agent-pi/src/production-goal.mjs b/apps/detail-agent-pi/src/production-goal.mjs index b4301a36..1bcb7bab 100644 --- a/apps/detail-agent-pi/src/production-goal.mjs +++ b/apps/detail-agent-pi/src/production-goal.mjs @@ -114,10 +114,10 @@ export async function runProductionGoal(host, text, images, userCanvasChanges) { const goal = !current || current.status === 'complete' || !current.objective.startsWith(objective) ? {id:randomUUID(),objective,status:'active'} : {...current,status:'active'}; if (goal.id !== current?.id || current.status !== goal.status) host.manager.appendCustomEntry('production-goal',{goal}); + const {product,dimensions,note,barcodeEntries,images:productImages,intake,barcodeBindings,detailBarcode,platformFacts}=host.productEvidence??{}; const context = {objective,...productionFacts(host.store,host.productionGoal), - requestedOutputs:host.productionGoal.requestedOutputs,product:host.productEvidence?.product, - platformFacts:host.productEvidence?.platformFacts, - intake:host.productEvidence?.intake,barcodeBindings:host.productEvidence?.barcodeBindings, + requestedOutputs:host.productionGoal.requestedOutputs,product,dimensions,note,barcodeEntries,images:productImages, + intake,barcodeBindings,detailBarcode,platformFacts, enterpriseKnowledge:host.productionSkills?.execution,userCanvasChanges}; await host.session.sendCustomMessage({customType:'photocraft-goal-request',content:JSON.stringify(context),display:false},{triggerTurn:false}); return host.session.prompt(text,{images}); @@ -232,13 +232,12 @@ export async function callProductionTool(host, name, args, signal) { if (name==='reconcile_image_slots')return reconcileProjectImageSlots(host,args,signal); if (name==='plan_production') { const {id,name,version,productionRoute}=goal.template??{}; - const {product,dimensions,note}=host.productEvidence??{}; + const {product,dimensions,note,barcodeEntries,images,intake,barcodeBindings,detailBarcode}=host.productEvidence??{}; const {referenceMode,mainImageAspects}=productionSettings(host.store,goal.template?.production); return {...productionFacts(host.store,goal),referenceMode:referenceMode??null,...(!referenceMode?{referenceNotice:'参考方式未声明'}:null), mainImageAspects:mainImageAspects??null,requestedOutputs:goal.requestedOutputs,pendingOutputs:goal.pendingOutputs, workingOutput:null,projectSlots:await projectSlotMap(host),template:{id,name,version,productionRoute}, - product:{...product,dimensions,note,...(host.productEvidence?.intake?{ - intake:host.productEvidence.intake,barcodeBindings:host.productEvidence.barcodeBindings}:null)}, + product:{...product,dimensions,note,barcodeEntries,images,intake,barcodeBindings,detailBarcode}, ...(host.productionSkills?.versionNotice?{knowledgeVersionNotice:host.productionSkills.versionNotice}:null), ...(args.includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null)}; } diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 57874ec7..9d2dd5c5 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -1,5 +1,5 @@ import { productionCopyCells, productionImageProgress, slotAttempts } from './production-progress.mjs'; -import { changedProductionFields, copyPage, productionInputs } from './production-copy.mjs'; +import { changedProductionFields, copyPage, matchesProductionInputs, productionInputs } from './production-copy.mjs'; import { allocateWorkerNumber, delegatePool } from './production-delegate.mjs'; import { createImageReconciler, expiryFields, imageOriginals, isLocalProductOperation, originalCandidate, readNativeOriginal, recoveryNotices, rememberImageExpiry, settledImagePhases, slotOriginals } from './image-reconciler.mjs'; import { candidateReceipt, compactProgress, imageResult, receiptPage, reviewSlotSummary } from './production-receipts.mjs'; @@ -99,7 +99,7 @@ export async function openProductionOperations(host,{target=host.productionConte const previous=ledger.read({readOnly}); let journal=previous?.binding===binding?previous:{binding,items:{}}; const evidenceMatches=(value,record=journal)=>Object.hasOwn(record,'copyInputs') - ?record.copyInputs===productionInputs(value,variantId) + ?matchesProductionInputs(value,variantId,record.copyInputs) :record.creationRevision===value.revisions?.creation; const syncCopyEvidence=(record,value)=>{ if(!evidenceMatches(value,record)){ @@ -276,15 +276,21 @@ export async function openProductionOperations(host,{target=host.productionConte }; const fieldRequirements=value=>Object.values(evidenceMatches(value)?journal.fieldRequirements??{}:{}); const productFacts=value=>{ - const brief=value.productEvidence?.brief??{}; - const dimensions=brief.dimensions??{}; - const variant=brief.variants?.find(row=>row.id===variantId); + const {brief,variant}=scopedProductionBrief(value.productEvidence?.brief??{},variantId,outputId); + const {barcodeEntries}=brief; + const [entry]=barcodeEntries; + const dimensions=barcodeEntries.length===1?entry.dimensions + : barcodeEntries.length===0?brief.dimensions??{}:{}; + const material=entry?.material??variant?.materialName; + const color=entry?.colorName??variant?.colorName; + const boardType=entry?.boardType; return Object.fromEntries([ ...Object.entries(dimensions).filter(([key,number])=>key!=='unit'&&String(number??'').trim()&&dimensions.unit) .map(([key,number])=>[({length:'长',width:'宽',height:'高'})[key]??key, {kind:'quantity',productValue:`${number} ${dimensions.unit}`}]), - ...(variant?.materialName?[['材质',{kind:'material',productValue:variant.materialName}]]:[]), - ...(variant?.colorName?[['颜色',{kind:'color',productValue:variant.colorName}]]:[]), + ...(material&&barcodeEntries.every(row=>row.material===material)?[['材质',{kind:'material',productValue:material}]]:[]), + ...(color&&barcodeEntries.every(row=>row.colorName===color)?[['颜色',{kind:'color',productValue:color}]]:[]), + ...(boardType&&barcodeEntries.every(row=>row.boardType===boardType)?[['板材类型',{kind:'material',productValue:boardType}]]:[]), ]); }; const screenFactConflicts=(fields,overlays,value,page)=>{ @@ -313,21 +319,22 @@ export async function openProductionOperations(host,{target=host.productionConte const journalCopy=Object.values(evidenceMatches(plan)?journal.copyEvidence??{}:{}); return resolveLiveSlotCopy({slot,copyFields,journalCopy}); }; - function screenReviewFingerprints(inputs){ + function screenReviewFingerprints(inputPlan){ + const inputs=productionInputs(inputPlan,variantId); return (journal.screenReviews??[]) - .filter(([,review])=>review.screenFingerprint&&review.copyInputs===inputs) + .filter(([,review])=>review.screenFingerprint&&matchesProductionInputs(inputPlan,variantId,review.copyInputs,inputs)) .map(([page,{screenFingerprint,issues}])=>({page:page+1,screenFingerprint, issues:issues.map(({reason,issue,...location})=>({...location,issue:issue??reason})), })); } const finishEvidence=inputPlan=>{ - const fingerprints=screenReviewFingerprints(productionInputs(inputPlan,variantId)); + const fingerprints=screenReviewFingerprints(inputPlan); const {mainImageAspects}=outputId==='main_images'?productionSettings(store,inputPlan.template.production):{}; return {...(fingerprints.length?{screenReviewFingerprints:fingerprints}:null), ...(mainImageAspects?{mainImageAspects}:null)}; }; const progressSummary=async()=>(await copySnapshot({ - screenReviewFingerprints:screenReviewFingerprints(productionInputs(plan,variantId)), + screenReviewFingerprints:screenReviewFingerprints(plan), })).progressSummary; let displayEpoch=0, progressVersion=0, progressSnapshot; const markProgressDirty=()=>{progressVersion++;}; @@ -364,7 +371,7 @@ export async function openProductionOperations(host,{target=host.productionConte } const readProgressSnapshot=async version=>{ const live=(journal.screenReviews??[]).some(([,review])=>review.screenFingerprint)?await readPlan():plan; - const reviews=evidenceMatches(live)?screenReviewFingerprints(productionInputs(live,variantId)):[]; + const reviews=evidenceMatches(live)?screenReviewFingerprints(live):[]; const snapshot=await copySnapshot({screenReviewFingerprints:reviews}); const copyCells=productionCopyCells(snapshot,reviews,journal.copyEvidence); return {version,revision:snapshot.revision,copyCells,summary:snapshot.progressSummary}; @@ -858,13 +865,7 @@ export async function openProductionOperations(host,{target=host.productionConte await current(); const {requested,matched,unmatched}=readSelection(slotIds); const {brief,variant}=scopedProductionBrief(plan.productEvidence?.brief??{},variantId,outputId); - const {name,spu,dimensions,note,intake,barcodes,detailBarcode,platformFacts,normalizedProduct}=brief; - const imageBindings=[...(brief.images??[]),...(variant?.images??[])] - .filter(image=>image.imageRole||image.barcode||image.kind) - .map(({name,purpose,imageRole,fieldKey,barcode,kind,label})=>({ - name,purpose,imageRole,fieldKey,barcode, - ...(kind?{kind}:null),...(label?{label}:null), - })); + const {name,spu,brand,category,dimensions,note,intake,barcodes,barcodeEntries,images,detailBarcode,platformFacts,normalizedProduct}=brief; const settings=productionSettings(store,plan.template.production); const {plannedSlots,...picturePlan}=productionPicturePlan(outputId,await liveSlots(),settings); const selected=plannedSlots.filter(slot=>!requested.size||matched.has(slot.id)); @@ -884,10 +885,9 @@ export async function openProductionOperations(host,{target=host.productionConte const {outputId:workingOutputId,variantId:workingVariantId}=context; return {outputId,variantId,workingOutput:workingOutputId?{outputId:workingOutputId,variantId:workingVariantId}:null, fieldConflicts:await fieldConflicts(await copySnapshot(),plan),fieldRequirements:fieldRequirements(plan), - template,product:{name,dimensions,note,...(spu?{spu}:null),variant:variant&&{id:variant.id,colorName:variant.colorName}, - ...(intake?{intake}:null),...(barcodes?{barcodes}:null),...(detailBarcode?{detailBarcode}:null), - ...(platformFacts?{platformFacts}:null),...(normalizedProduct?{normalizedProduct}:null), - ...(imageBindings.length?{imageBindings}:null)}, + template,product:{name,spu,brand,category,dimensions,note,barcodeEntries,images,intake,barcodes, + variant:variant&&{id:variant.id,colorName:variant.colorName},...(detailBarcode?{detailBarcode}:null), + ...(platformFacts?{platformFacts}:null),...(normalizedProduct?{normalizedProduct}:null)}, candidatesPerSlot,maxCandidatesPerSlot,maxGenerationAttempts,generationLimitSource,...picturePlan,...facts(),...(productUpdate?{productUpdate}:null),pictures, inFlightImages:(await pendingNative()).map(row=>row.candidateId), ...(includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null), diff --git a/apps/detail-agent-pi/src/production-repository.mjs b/apps/detail-agent-pi/src/production-repository.mjs index a4f30568..a3a7b476 100644 --- a/apps/detail-agent-pi/src/production-repository.mjs +++ b/apps/detail-agent-pi/src/production-repository.mjs @@ -2,7 +2,7 @@ import fs from 'node:fs/promises'; import path from 'node:path'; import { ProjectRepository } from './project-repository.mjs'; import { atomic, digest } from './store.mjs'; -import { briefBarcodeBindings, briefVariants, detailBarcode, normalizedProductEvidence, projectSpu, variantBarcodes } from './product-brief.mjs'; +import { briefBarcodeBindings, briefBarcodeEntries, briefVariants, canonicalProductBrief, detailBarcode, legacyProductEvidence, productImageEvidence, variantBarcodes, variantColorName } from './product-brief.mjs'; export function productionRepository(store, outputId, variantId) { const { scope: accountId, project: projectId } = store.identity; @@ -40,41 +40,39 @@ export function productionLedger(store, outputId, variantId) { } export function scopedProductionBrief(source, variantId, outputId) { - const { variants, intake, barcodeBindings, detailBarcode: selectedBarcode, deliverySpu, - normalizedProduct, platformFacts, ...brief } = source; - const spu = projectSpu(source); - if (spu) brief.spu = spu; + const { variants, barcodeBindings, detailBarcode: selectedBarcode, deliverySpu, + normalizedProduct, platformFacts, sourceSnapshot, ...brief } = source; + const entries = briefBarcodeEntries(source); const matchedVariant = briefVariants(source).find(row => row.id === variantId); - const variant = Array.isArray(variants) || !matchedVariant ? matchedVariant - : { id: matchedVariant.id, colorName: matchedVariant.colorName }; - const selected = outputId === 'detail' ? detailBarcode(source) : undefined; - const boundBarcodes = variantBarcodes(source, variantId); + const selected = outputId === 'detail' ? detailBarcode(source, entries) : undefined; + const boundBarcodes = variantBarcodes(source, variantId, briefBarcodeBindings(source, entries)); if (outputId === 'detail' && !selected && boundBarcodes.length) { throw Error('请在产品资料中选择制作详情页的主条码'); } if (selected && !boundBarcodes.includes(selected)) throw Error('当前详情花色不包含选定的主条码'); const barcodes = selected ? [selected] : boundBarcodes; + const scope = { variantId, barcodes }; + const canonical = canonicalProductBrief(source, scope, entries); + Object.assign(brief, canonical, legacyProductEvidence(source, canonical.images, scope)); + brief.images = canonical.images.map(productImageEvidence); if (selected) brief.detailBarcode = selected; - if (briefBarcodeBindings(source)) brief.barcodes = barcodes; - const normalized = normalizedProductEvidence(normalizedProduct, { variantId, barcodes }); - const assetIds = new Set(normalized?.assets.map(asset => asset.id)); - if (Array.isArray(brief.images)) brief.images = brief.images.filter(image => - !image.barcode || barcodes.includes(image.barcode) || assetIds.has(image.assetId)); - if (normalized) { - brief.normalizedProduct = normalized; - } else if (platformFacts) { - const {shared,barcodes:rows}=platformFacts; - const safeRows = rows && typeof rows === 'object' ? rows : {}; - brief.platformFacts={shared,barcodes:Object.fromEntries(barcodes.filter(code=>Object.hasOwn(safeRows,code)).map(code=>[code,safeRows[code]]))}; + brief.barcodes = barcodes; + const [entry] = canonical.barcodeEntries; + if (canonical.barcodeEntries.length === 1) { + brief.dimensions = entry.dimensions; + brief.colorName = entry.colorName; + } else if (Array.isArray(source.barcodeEntries) && entries.length) { + delete brief.dimensions; + delete brief.colorName; } - if (intake) { - const values = intake.barcodeValues && typeof intake.barcodeValues === 'object' ? intake.barcodeValues : {}; - const barcodeValues = Object.fromEntries(barcodes - .filter(barcode => Object.hasOwn(values, barcode)) - .map(barcode => [barcode, values[barcode]])); - brief.intake = { ...intake, barcodeValues }; + if (matchedVariant) { + const { id, colorName, images, materialName, ...details } = matchedVariant; + const variant = { ...(Array.isArray(variants) ? details : null), id, + colorName: variantColorName(matchedVariant, canonical.barcodeEntries) }; + if (!canonical.barcodeEntries.length && materialName) variant.materialName = materialName; + return { brief, variant }; } - return { brief, variant }; + return { brief, variant: undefined }; } export function recordProductionInputs(repository, plan, slots) { diff --git a/apps/detail-agent-pi/src/production-screen-tools.mjs b/apps/detail-agent-pi/src/production-screen-tools.mjs index 0be34780..8dd456c6 100644 --- a/apps/detail-agent-pi/src/production-screen-tools.mjs +++ b/apps/detail-agent-pi/src/production-screen-tools.mjs @@ -1,7 +1,7 @@ import { formatDimensionNote, resizeImage } from '@earendil-works/pi-coding-agent'; import { isDeepStrictEqual } from 'node:util'; import { extractPageLiveCopy } from './copy-image-alignment.mjs'; -import { productionInputs } from './production-copy.mjs'; +import { matchesProductionInputs, productionInputs } from './production-copy.mjs'; import { scopedProductionBrief } from './production-repository.mjs'; import { imageResult } from './production-receipts.mjs'; import { reviewOutputScreen, summarizeOverlayGroups } from './screen-review.mjs'; @@ -111,13 +111,13 @@ export function createProductionScreenTools({ previous.screenFingerprint===screenFingerprint && isDeepStrictEqual(requirements,previous.receipt.fieldRequirements??[]) && isDeepStrictEqual(slotImageFacts??[],previous.slotImageFacts??[]) && - previous.copyInputs===productionInputs(await current(),variantId)){ + matchesProductionInputs(await current(),variantId,previous.copyInputs)){ job.receipt={...previous.receipt,revision,...screenReviewFacts(page-1),reused:true}; return; } if(previous?.candidateReview && !slotImageFacts?.length && (!screen.details.templateFidelity || previous.candidateReview.templateEvidence) && !screen.details.screenChanged && previous.screenFingerprint===screen.details.screenFingerprint && - previous.copyInputs===productionInputs(await current(),variantId)){ + matchesProductionInputs(await current(),variantId,previous.copyInputs)){ job.receipt={...previous.candidateReview,...screenReviewFacts(page-1),revision:screen.details.revision,...(screen.details.fieldRequirements?{fieldRequirements:screen.details.fieldRequirements}:null),reused:true}; return; } diff --git a/apps/detail-agent-pi/src/project-context.mjs b/apps/detail-agent-pi/src/project-context.mjs index 17254279..47a26161 100644 --- a/apps/detail-agent-pi/src/project-context.mjs +++ b/apps/detail-agent-pi/src/project-context.mjs @@ -1,5 +1,5 @@ import { digest } from './store.mjs'; -import { briefBarcodeBindings, briefVariants, detailBarcode, normalizedProductEvidence, projectSpu, splitBarcodes, variantBarcodes } from './product-brief.mjs'; +import { briefBarcodeBindings, briefVariants, canonicalProductBrief, detailBarcode, legacyProductEvidence, productImageEvidence, variantBarcodes, variantColorName } from './product-brief.mjs'; const text=value=>typeof value==="string"?value:""; const list=value=>Array.isArray(value)?value:[]; @@ -9,16 +9,6 @@ const outputColors=value=>Object.fromEntries(['detail','sku_images','main_images const raw=value?.[key], color=safeText(raw); return color||raw===''?[[key,color]]:[]; })); -const images=(value,variantId)=>list(value).filter(image=>image&&typeof image==='object').map(image=>({ - ...(typeof image.ref==='string'&&/^sha256:[a-f0-9]{64}$/.test(image.ref)?{ref:image.ref}:{}), - ...(['product','scene'].includes(image.purpose)?{purpose:image.purpose}:{}), - ...(safeText(image.name)?{name:safeText(image.name)}:{}), - ...(safeText(image.description)?{description:safeText(image.description)}:{}), - ...(!(typeof image.ref==='string'&&/^sha256:[a-f0-9]{64}$/.test(image.ref))?{missing:['参考图稳定身份未提供']}:{}), - ...Object.fromEntries(['imageRole','fieldKey','templateId','barcode','kind','assetId'].filter(key=>typeof image[key]==='string') - .map(key=>[key,image[key]])), - scope:image.barcode?'barcode':variantId?'variant':'common',...(variantId?{variantId}:{}), -})); /** Data-only product evidence. Never includes pixels, complete brand prompts, * request bodies, credentials or model task journals. */ @@ -27,15 +17,20 @@ export function productContext(value,identity){ if(value.accountScope!==identity.scope||value.project!==identity.project||!Number.isSafeInteger(value.documentId)||value.documentId!==identity.documentId)throw Error('产品上下文不属于当前账户和项目'); const brief=value.brief||{},facts=value.facts||{},selling=value.sellingPoints||{},plan=value.plan||{}; const skuPlan=brief.outputVariantIds&&typeof brief.outputVariantIds==='object'&&!Array.isArray(brief.outputVariantIds); - const normalized = normalizedProductEvidence(brief.normalizedProduct); - const rawVariants=briefVariants(brief); - const variants=list(rawVariants).filter(v=>v&&safeId(v.id)).map(v=>({id:v.id, - ...(safeText(v.name)?{name:safeText(v.name)}:{}), - ...(safeText(v.colorName)?{colorName:safeText(v.colorName)}:{}), - ...(!skuPlan&&v.outputColors?{outputColors:outputColors(v.outputColors)}:{}), - ...(safeId(v.colorMaterialId)?{colorMaterialId:v.colorMaterialId}:{}), - images:images(v.images,v.id),...(Array.isArray(v.images)?{}:{missing:['花色参考图资料未提供']})})); - const commonImages=images(brief.images); + const { name, spu, brand, category, note, barcodeEntries, images, intake } = canonicalProductBrief(brief); + const bindings = briefBarcodeBindings(brief, barcodeEntries); + const selectedBarcode = detailBarcode(brief, barcodeEntries); + const selectedEntry = barcodeEntries.find(row => row.barcode === selectedBarcode); + const dimensions = selectedEntry?.dimensions ?? (Array.isArray(brief.barcodeEntries)&&barcodeEntries.length ? undefined : brief.dimensions); + const variants=briefVariants(brief).filter(v=>safeId(v.id)).map(v=>{ + const barcodes=variantBarcodes(brief,v.id,bindings); + const colorName=safeText(variantColorName(v,barcodeEntries.filter(row=>barcodes.includes(row.barcode)))); + return {id:v.id,...(safeText(v.name)?{name:safeText(v.name)}:{}),...(colorName?{colorName}:{}), + ...(!skuPlan&&v.outputColors?{outputColors:outputColors(v.outputColors)}:{}), + ...(safeId(v.colorMaterialId)?{colorMaterialId:v.colorMaterialId}:{}), + ...(images.some(image=>image.variantId===v.id||barcodes.includes(image.barcode))||Array.isArray(v.images) + ?{}:{missing:['花色参考图资料未提供']})}; + }); const selected=[]; for(const key of list(selling.selected)){ if(typeof key!=='string')continue; @@ -44,24 +39,20 @@ export function productContext(value,identity){ if(split>0&&Number.isInteger(index)&&index>=0&&typeof batch?.items?.[index]==='string')selected.push(text(batch.items[index])); } const result={state:'ready',authority:'当前项目只读资料;品牌规范不是产品事实,模型提取仍需保留其来源与待确认项。',documentId:value.documentId,revision:value.revision, - product:Object.fromEntries(['name','brandId','brandName','categoryId','categoryName','identifierType','identifier','variant','colorName'].map(key=>[key,text(brief[key])])), - dimensions:Object.fromEntries(['length','width','height','unit'].map(key=>[key,text(brief.dimensions?.[key])])),note:text(brief.note), + product:{...Object.fromEntries(['brandId','categoryId','identifierType','identifier','variant'].map(key=>[key,text(brief[key])])), + name,spu,brand,category,brandName:brand,categoryName:category,colorName:selectedEntry?.colorName??text(brief.colorName)}, + dimensions:Object.fromEntries(['length','width','height','unit'].map(key=>[key,text(dimensions?.[key])])),note, + barcodeEntries, images:images.map(productImageEvidence), intake, references:{source:'当前项目产品资料;图片内容和路径未提供,不能据此推断外观。', - variants,commonImages,...(safeId(value.currentVariantId)&&variants.some(v=>v.id===value.currentVariantId)?{currentVariantId:value.currentVariantId}:{}), - missing:[...(!Array.isArray(brief.variants)&&!normalized?['花色资料未提供']:[]),...(!Array.isArray(brief.images)?['共用参考图资料未提供']:[])]}, + variants,...(safeId(value.currentVariantId)&&variants.some(v=>v.id===value.currentVariantId)?{currentVariantId:value.currentVariantId}:{}), + missing:[...(!variants.length&&!Array.isArray(brief.variants)?['花色资料未提供']:[]),...(!images.length&&!Array.isArray(brief.images)?['共用参考图资料未提供']:[])]}, factsStatus:text(facts.status),facts:list(facts.items).map(f=>({text:text(f.text),source:text(f.source)})), missing:list(facts.missing).map(v=>text(v)),selectedSellingPoints:selling.stale?[]:selected, plan:{status:text(plan.status),screens:list(plan.screens).map(s=>({name:text(s.name||s.title),body:text(s.body)}))}}; - if(normalized) result.normalizedProduct=normalized; - else if(brief.platformFacts) result.platformFacts=brief.platformFacts; - if(brief.intake) result.intake=brief.intake; - const bindings=briefBarcodeBindings(brief); - if(bindings) result.barcodeBindings=Object.fromEntries( - Object.entries(bindings).map(([variantId, binding])=>[variantId,splitBarcodes(binding)])); - const selectedBarcode=detailBarcode(brief), spu=projectSpu(brief); + Object.assign(result,legacyProductEvidence(brief,images)); + if(barcodeEntries.length||brief.barcodeBindings) result.barcodeBindings=bindings; if(selectedBarcode) result.detailBarcode=selectedBarcode; - if(spu) result.product.spu=spu; - const detailVariant=selectedBarcode&&variants.find(variant=>variantBarcodes(brief,variant.id).includes(selectedBarcode)); + const detailVariant=selectedBarcode&&variants.find(variant=>variantBarcodes(brief,variant.id,bindings).includes(selectedBarcode)); if(skuPlan||detailVariant)result.references.outputVariantIds=Object.fromEntries(['detail','main_images'].flatMap(key=>{ const ids=key==='detail'&&detailVariant?[detailVariant.id]:list(brief.outputVariantIds?.[key]).map(safeId).filter(Boolean); return ids.length?[[key,ids]]:[]; diff --git a/apps/detail-agent-pi/test/product-brief.test.mjs b/apps/detail-agent-pi/test/product-brief.test.mjs index 068c64be..afd4e313 100644 --- a/apps/detail-agent-pi/test/product-brief.test.mjs +++ b/apps/detail-agent-pi/test/product-brief.test.mjs @@ -1,7 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import fixture from '../../../lib/__tests__/fixtures/xiaoyi-free-barcode.json' with { type: 'json' }; -import { detailBarcode, projectSpu, splitBarcodes, variantBarcodes } from '../src/product-brief.mjs'; +import { canonicalProductBrief, detailBarcode, projectSpu, splitBarcodes, variantBarcodes } from '../src/product-brief.mjs'; import { scopedProductionBrief } from '../src/production-repository.mjs'; import { intakeMetadata } from '../src/enterprise-templates.mjs'; import { productContext } from '../src/project-context.mjs'; @@ -77,11 +77,12 @@ test('template image fields and scoped evidence preserve role, slot, and barcode ]; const source = {...brief,images,intake:{...brief.intake,schema},platformFacts:{shared:{material:'棉'},barcodes:{[other]:{colorName:'白色'},[white]:{colorName:'蓝色'}}}}; const context = productContext({accountScope:'a',project:'p',documentId:1,brief:source},{scope:'a',project:'p',documentId:1}); - assert.equal(context.references.commonImages[1].scope,'barcode'); - assert.equal(context.references.commonImages[1].barcode,other); - assert.equal(context.references.commonImages[1].imageRole,'material'); + assert.equal(context.images[1].scope,'barcode'); + assert.equal(context.images[1].barcode,other); + assert.equal(context.images[1].imageRole,'material'); const {brief:detail} = scopedProductionBrief(source,'white','detail'); - assert.deepEqual(detail.images,images.slice(0,2)); + assert.deepEqual(detail.images.map(({name,barcode,fieldKey})=>({name,barcode,fieldKey})), + images.slice(0,2).map(({name,barcode,fieldKey})=>({name,barcode,fieldKey}))); assert.deepEqual(detail.platformFacts,{shared:{material:'棉'},barcodes:{[other]:{colorName:'白色'}}}); }); @@ -154,11 +155,117 @@ test('normalized production briefs retain shared assets and image references fro assert.deepEqual(detail.barcodes, [other]); assert.deepEqual(detail.normalizedProduct.variants[0].barcodes.map(row => row.barcode), [other]); assert.deepEqual(detail.normalizedProduct.assets.map(asset => asset.id), ['common', 'white-image']); - assert.deepEqual(detail.images, [sharedImage]); + assert.deepEqual(detail.images.map(({id,barcode})=>[id,barcode]), [['white-image',white],['common',undefined]]); assert.deepEqual(scopedProductionBrief(source, 'black', 'sku_images').brief.normalizedProduct.assets.map(asset => asset.id), ['common', 'black-image']); }); +test('manual, platform, and library briefs have the same canonical schema and scoped evidence', () => { + const name = '实木书桌', spu = 'T01', brand = '甲品牌', category = '书桌', note = '沿用实拍花色'; + const dimensions = { length: '140', width: '70', height: '75', unit: 'cm' }; + const barcodeEntries = [{ barcode: other, colorName: '白蜡木', dimensions, material: '实木', boardType: '指接板' }]; + const localSource = 'local:' + 'b'.repeat(64); + const asset = { id: 'hero', name: '正面', source: localSource, purpose: 'product', + origin: 'product_platform', kind: 'whiteBackground', barcode: other }; + const intake = { productValues: { origin: '佛山' }, barcodeValues: { [other]: { seating: 2 } } }; + const manual = { source: 'manual', name, spu, brand, category, note, barcodeEntries, images: [asset], intake }; + const platform = { + source: 'product_platform', note, intake, + normalizedProduct: { + identity: { productName: name, spu, platformBrand: brand, platformCategory: category }, + variants: [{ id: 'default', colorName: '白蜡木', barcodes: [{ barcode: other, + dimensions: { length: 140, width: 70, height: 75, unit: 'CM' }, material: '实木', boardType: '指接板' }] }], + assets: [{ id: asset.id, name: asset.name, localSource, kind: 'whiteBackground', barcode: other }], + }, + }; + const library = { source: 'library', name, identifierType: 'spu', identifier: spu, brandName: brand, categoryName: category, + note, barcodeEntries, images: [asset], intake }; + const expected = canonicalProductBrief(manual); + assert.deepEqual(expected, { name, spu, brand, category, note, barcodeEntries, intake, + images: [{ ...asset, selected: true, scope: 'barcode' }] }); + for (const source of [manual, platform, library]) { + assert.deepEqual(canonicalProductBrief(source), expected); + const context = productContext({ accountScope: 'a', project: 'p', documentId: 1, brief: source }, + { scope: 'a', project: 'p', documentId: 1 }); + const { brief: scoped } = scopedProductionBrief(source, 'default', 'detail'); + assert.deepEqual(context.barcodeEntries, barcodeEntries); + assert.equal(context.product.brandName, brand); + assert.equal(context.product.categoryName, category); + assert.deepEqual(scoped.barcodeEntries, barcodeEntries); + assert.deepEqual(context.images, scoped.images); + assert.equal(context.images[0].source, localSource); + assert.equal(context.detailBarcode, other); + assert.deepEqual(scoped.intake, intake); + } +}); + +test('legacy barcode sources are united without mutation and keep exact codes, dimensions, and answers', () => { + const source = { + name: '旧书桌', variants: [{ id: 'white', colorName: '白色' }], barcodeBindings: { white: ['00,1', '0002'] }, + normalizedProduct: { + variants: [{ id: 'white', colorName: '白色', barcodes: [{ barcode: '00,1', + dimensions: { length: 1400, unit: 'mm' }, attributes: [{ key: 'board_type', value: '实木板' }] }] }], + }, + platformFacts: { shared: { material: '白蜡木' }, barcodes: { + '00,1': { dimensions: { width: 80, height: 75, unit: '厘米' } }, '00C': { colorName: '暖白' }, + } }, + intake: { schema: { barcodeFields: [{ key: 'width', unit: 'cm' }] }, + productValues: { packing: '纸箱' }, barcodeValues: { '00,1': { width: 72.5, extra: '保留' }, '00c': { material: '橡木' } } }, + }; + const original = structuredClone(source); + const result = canonicalProductBrief(source); + assert.deepEqual(result.barcodeEntries.map(row => row.barcode), ['00,1', '0002', '00C', '00c']); + assert.deepEqual(result.barcodeEntries[0], { barcode: '00,1', colorName: '白色', + dimensions: { length: '1400', width: '725', height: '750', unit: 'mm' }, material: '白蜡木', boardType: '实木板' }); + assert.deepEqual(result.intake, source.intake); + assert.deepEqual(source, original); + assert.equal(result.barcodeEntries[3].material, '橡木'); + assert.deepEqual(scopedProductionBrief(source, 'white', 'sku_images').brief.barcodes, ['00,1', '0002', '00C', '00c']); +}); + +test('persisted barcode edits, removals, and explicit blanks take precedence over stale snapshots', () => { + const source = { ...brief, name: '桌子', normalizedProduct, detailBarcode: other, dimensions: { length: '1400', unit: 'mm' }, + barcodeEntries: [{ barcode: '', colorName: '' }, + { barcode: other, variantId: 'black', colorName: '用户改的花色', dimensions: { length: 128, unit: 'cm' }, + material: '', boardType: '用户选的板材' }], + platformFacts: { barcodes: { [other]: { material: '旧材质', boardType: '旧板材' } } }, + intake: { barcodeValues: { [other]: { length: 1400, material: '旧材质' } } }, + }; + const entry = { barcode: other, colorName: '用户改的花色', dimensions: { length: '128', width: '', height: '', unit: 'cm' }, + material: '', boardType: '用户选的板材' }; + const context = productContext({ accountScope: 'a', project: 'p', documentId: 1, brief: source }, + { scope: 'a', project: 'p', documentId: 1 }); + assert.deepEqual(context.barcodeEntries, [entry]); + assert.deepEqual(context.barcodeBindings, { black: [other] }); + assert.deepEqual(context.dimensions, entry.dimensions); + assert.equal(context.product.colorName, entry.colorName); + assert.equal(context.normalizedProduct, undefined); + assert.equal(context.platformFacts, undefined); + const scoped = scopedProductionBrief(source, 'black', 'detail'); + assert.deepEqual(scoped.brief.barcodeEntries, [entry]); + assert.equal(scoped.variant.colorName, entry.colorName); + assert.throws(() => scopedProductionBrief(source, 'white', 'detail'), /不包含选定的主条码/); + assert.deepEqual(canonicalProductBrief({ ...source, barcodeEntries: [] }).barcodeEntries, []); +}); + +test('the image pool merges image aliases, honors deselection, and keeps different field bindings', () => { + const hash = 'a'.repeat(64); + const source = { normalizedProduct: { assets: [ + { id: 'linked', localSource: 'local:' + hash, label: '旧名称', kind: 'reference', selectedForProject: true }, + { id: 'off', selectedForProject: false }, { id: 'retired', selectedForProject: true }, + ] }, images: [ + { ref: 'sha256:' + hash, name: '用户命名', fieldKey: 'hero', purpose: 'product', origin: 'library' }, + { assetId: 'linked', source: 'local:' + hash, fieldKey: 'hero', purpose: 'product' }, + { assetId: 'linked', source: 'local:' + hash, fieldKey: 'texture', purpose: 'scene' }, + { assetId: 'off', name: '已取消' }, { assetId: 'retired', selected: false }, + ] }; + const { images } = canonicalProductBrief(source); + assert.deepEqual(images.map(({id,fieldKey,purpose})=>[id,fieldKey,purpose]), + [['linked','hero','product'],['linked','texture','scene']]); + assert.equal(images[0].name, '用户命名'); + assert.equal(images[0].origin, 'library'); +}); + test('intakeMetadata promotes hint aliases into placeholder without overwriting explicit placeholder', () => { const schema = intakeMetadata({ version: 1, diff --git a/apps/detail-agent-pi/test/production-goal.test.mjs b/apps/detail-agent-pi/test/production-goal.test.mjs index 509fe44b..dc6a4e03 100644 --- a/apps/detail-agent-pi/test/production-goal.test.mjs +++ b/apps/detail-agent-pi/test/production-goal.test.mjs @@ -6,6 +6,7 @@ import path from 'node:path'; import { productionObjective, runProductionGoal, callProductionTool } from '../src/production-goal.mjs'; import { completeCanvas } from './fake-canvas.mjs'; import { productionStore } from './production-store-fixture.mjs'; +import { productContext } from '../src/project-context.mjs'; test('a partial delivery keeps its files and concrete missing items without completing the goal',async()=>{ const receipt={finalized:true,complete:true,completed:true,allOutputsCompleted:false, @@ -72,3 +73,30 @@ test('a resumed production goal receives specific user canvas changes before res assert.equal(calls[1],'继续制作'); assert.equal(calls[0].display,false); }); + +test('the goal request and plan without an open output both receive the canonical brief', async t => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xiaoyi-canonical-goal-')); + t.after(() => fs.rm(dir, { recursive: true, force: true })); + const identity = { scope: 'a', project: 'p', documentId: 1 }; + const barcodeEntries = [{ barcode: '001', colorName: '雾白', material: '白蜡木', boardType: '指接板', + dimensions: { length: '120', width: '70', height: '75', unit: 'cm' } }]; + const brief = { name: '书桌', spu: 'A01', brand: '甲品牌', category: '书桌', note: '保留原木纹理', barcodeEntries, + images: [{ id: 'hero', name: '实拍', origin: 'library', purpose: 'product' }] }; + const productEvidence = productContext({ ...identity, accountScope: identity.scope, brief }, identity); + const sent = []; + const host = { + store: productionStore(dir), productionGoal: { requestedOutputs: [] }, productEvidence, + manager: { getBranch: () => [], appendCustomEntry() {} }, + session: { sendCustomMessage: async message => sent.push(JSON.parse(message.content)), prompt: async () => {} }, + }; + await runProductionGoal(host, '制作', []); + const plan = await callProductionTool(host, 'plan_production', {}); + for (const evidence of [sent[0], plan.product]) { + assert.deepEqual(evidence.barcodeEntries, barcodeEntries); + assert.deepEqual(evidence.images, productEvidence.images); + assert.equal(evidence.detailBarcode, '001'); + assert.deepEqual(evidence.intake, { productValues: {}, barcodeValues: {} }); + } + assert.equal(sent[0].product.brand, '甲品牌'); + assert.equal(plan.product.note, brief.note); +}); diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs index e6bbf079..6710f0fa 100644 --- a/apps/detail-agent-pi/test/production-operations.test.mjs +++ b/apps/detail-agent-pi/test/production-operations.test.mjs @@ -1560,8 +1560,14 @@ test('a sibling variant edit leaves the current plan usable, and a local edit ca let actions=await openProductionOperations(host); const initialPlan=await actions.plan_production(); assert.deepEqual(initialPlan.pendingOutputs,[nextOutput]); - assert.deepEqual(initialPlan.product,{name:'餐桌',dimensions,note,variant:{id:variantId,colorName:'橡木色'}, - barcodes:['DNZ030516N717V01','CY001307N35V01'],intake:{...intake,barcodeValues:{'DNZ030516N717V01':{width:'120'},'CY001307N35V01':{width:'140'}}}}); + assert.equal(initialPlan.product.name,'餐桌'); + assert.deepEqual(initialPlan.product.dimensions,dimensions); + assert.equal(initialPlan.product.note,note); + assert.deepEqual(initialPlan.product.variant,{id:variantId,colorName:'橡木色'}); + assert.deepEqual(initialPlan.product.barcodes,['DNZ030516N717V01','CY001307N35V01']); + assert.deepEqual(initialPlan.product.barcodeEntries.map(row=>[row.barcode,row.dimensions.width,row.dimensions.unit]), + [['DNZ030516N717V01','120','mm'],['CY001307N35V01','140','mm']]); + assert.deepEqual(initialPlan.product.intake,{...intake,barcodeValues:{'DNZ030516N717V01':{width:'120'},'CY001307N35V01':{width:'140'}}}); intake.barcodeValues['SG008839N1049V01'].width='170'; creation++; assert.equal((await actions.plan_production()).productUpdate,undefined); @@ -1613,7 +1619,7 @@ test('a sibling variant edit leaves the current plan usable, and a local edit ca assert.equal(submissions.length,2); const plan=await actions.plan_production(); assert.equal(plan.product.variant.colorName,'烟熏橡木'); - assert.deepEqual(plan.productUpdate,{previousVersion:2,currentVersion:3,changedFields:['variant.colorName']}); + assert.deepEqual(plan.productUpdate,{previousVersion:2,currentVersion:3,changedFields:['brief.barcodeEntries','variant.colorName']}); const reopened=await openProductionOperations(host); await reopened.finish_production({revision:3}); assert.equal((await journal()).copyEvidence,undefined); @@ -2692,13 +2698,49 @@ test('plan_production forwards scoped normalizedProduct and normalized image kin const plan = await actions.plan_production(); assert.equal(plan.product.normalizedProduct.identity.spu, 'A01'); assert.deepEqual(plan.product.normalizedProduct.assets.map(a => a.id), ['common-img', 'white-img']); - assert.deepEqual(plan.product.imageBindings, [{ - name: '白底主图', - purpose: 'product', - imageRole: undefined, - fieldKey: undefined, - barcode, - kind: 'whiteBackground', - label: '白底图 · 白色', - }]); + assert.deepEqual(plan.product.images.map(({id,name,purpose,barcode,kind})=>({id,name,purpose,barcode,kind})), [ + { id: 'white-img', name: '白底主图', purpose: 'product', barcode, kind: 'whiteBackground' }, + { id: 'common-img', name: '主图', purpose: 'scene', barcode: undefined, kind: 'main' }, + ]); + assert.equal(plan.product.barcodeEntries[0].material, '实木'); +}); + +test('plan_production compares copy fields with the selected canonical barcode edits', async t => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-canonical-plan-')); + t.after(() => cleanup(dir)); + const store = productionStore(dir); + const barcode = '001,A'; + const entry = { barcode, colorName: '暖白', dimensions: { length: '125', width: '', height: '', unit: 'cm' }, + material: '白蜡木', boardType: '指接板' }; + const host = { + store, + productionGoal: { outputId: 'detail', variantId: 'white' }, + canvas: { + workflowRead: async () => ({ + available: true, canvasFirst: true, outputId: 'detail', productVariantId: 'white', totalSlots: 0, slots: [], + template: { contentHash: 'canonical' }, + productEvidence: { brief: { name: '书桌', detailBarcode: barcode, + barcodeEntries: [{ ...entry, variantId: 'white' }, { barcode: '002', variantId: 'black' }], + dimensions: { length: '1400', unit: 'mm' }, + variants: [{ id: 'white', colorName: '旧花色', materialName: '旧材质' }], + platformFacts: { barcodes: { [barcode]: { boardType: '旧板材' } } }, + } }, + }), + detailCopyFields: async () => ({ fields: [ + { layer: 1, label: '长', originalText: '1400 mm' }, + { layer: 2, label: '颜色', originalText: '旧花色' }, + { layer: 3, label: '材质', originalText: '旧材质' }, + { layer: 4, label: '板材类型', originalText: '旧板材' }, + ] }), + delta: async () => {}, + imageRequest: async () => [], + }, + }; + const actions = await openOperations(host); + t.after(() => actions.close()); + const plan = await actions.plan_production(); + assert.deepEqual(plan.product.barcodeEntries, [entry]); + assert.deepEqual(plan.product.dimensions, entry.dimensions); + assert.deepEqual(plan.fieldConflicts.map(({ layer, productValue }) => [layer, productValue]), + [[1, '125 cm'], [2, '暖白'], [3, '白蜡木'], [4, '指接板']]); });