合入交付包去重、短路径与按引用精简候选(R5-Z17)

This commit is contained in:
WuYongJie 2026-11-29 02:54:19 +08:00
commit 48bed2e445
6 changed files with 340 additions and 92 deletions

View File

@ -76,6 +76,9 @@ export async function verifyDeliveryBundle(directory, expected = []) {
let missing = [];
let project;
let bundle;
let longestRelativePath = '';
const largeFiles = new Map();
const duplicateLargeFiles = [];
try {
bundle = JSON.parse(await readFile(path.join(root, '交付清单.json'), 'utf8'));
requireThat(bundle.version === 1 && typeof bundle.deliveryId === 'string' && bundle.deliveryId
@ -111,6 +114,11 @@ export async function verifyDeliveryBundle(directory, expected = []) {
const hash = createHash('sha256');
for await (const chunk of createReadStream(file)) hash.update(chunk);
requireThat(hash.digest('hex') === sha256, 'SHA-256 与清单不符');
if (sizeBytes >= 10 * 1024 * 1024) {
const previous = largeFiles.get(sha256);
if (previous) duplicateLargeFiles.push([previous, relativePath]);
else largeFiles.set(sha256, relativePath);
}
if (format === 'xiaoyi') {
requireThat(!project && category === '工程文件' && path.posix.dirname(relativePath) === '工程文件', '工程入口无效或重复');
project = JSON.parse(await readFile(file, 'utf8'));
@ -130,7 +138,10 @@ export async function verifyDeliveryBundle(directory, expected = []) {
const checkpoint = `工程文件/${project.resources}/${project.snapshot}`;
requireThat((await stat(path.join(root, checkpoint))).isDirectory(), '工程资源目录缺失');
requireThat(project.projectManifest.included.includes('canvas.pcraft')
&& project.projectManifest.included.every(name => entries.get(`${checkpoint}/${name}`)?.category === '工程资源'), '工程资源未完整列入交付清单');
&& project.projectManifest.included.every(name => {
if (!project.resourcePaths) return entries.get(`${checkpoint}/${name}`)?.category === '工程资源';
return entries.get(project.resourcePaths[name])?.format === path.posix.extname(name).slice(1);
}), '工程资源未完整列入交付清单');
const selected = new Set();
let outputCount = 0;
for (const [relativePath, record] of entries) {
@ -148,12 +159,22 @@ export async function verifyDeliveryBundle(directory, expected = []) {
}
}
for (const entry of await readdir(root, { recursive: true, withFileTypes: true })) {
if (!entry.isFile()) continue;
const relativePath = path.relative(root, path.join(entry.parentPath, entry.name)).split(path.sep).join('/');
if (relativePath.length > longestRelativePath.length) longestRelativePath = relativePath;
if (/[a-f0-9]{64}/i.test(entry.name)) {
errors.push({ path: relativePath, message: '文件名或目录名含 64 位哈希', missing: false });
}
if (!entry.isFile()) continue;
if (relativePath !== '交付清单.json' && !entries.has(relativePath)) {
errors.push({ path: relativePath, message: '磁盘文件未列入清单', missing: false });
}
}
if (longestRelativePath.length > 120) {
errors.push({ path: longestRelativePath, message: '相对路径超过 120 字符', missing: false });
}
for (const [previous, duplicate] of duplicateLargeFiles) {
errors.push({ path: duplicate, message: `大文件内容重复:${previous}`, missing: false });
}
requireThat(outputCount === bundle.completedOutputs, '磁盘输出数与清单不符');
for (const id of expected) {
if (!selected.has(id)) errors.push({ outputId: id, message: `缺少期望输出 ${id}`, missing: true });
@ -162,6 +183,7 @@ export async function verifyDeliveryBundle(directory, expected = []) {
errors.push({ message: error.message, missing: error.code === 'ENOENT' || error.message.startsWith('缺少') });
}
return { ok: errors.length === 0 && missingOutputs === 0, deliveryDir: root, counts, files, missingOutputs, missing,
longestRelativePath, longestRelativePathLength: longestRelativePath.length, duplicateLargeFiles,
failedCount: errors.filter(error => !error.missing).length,
missingCount: errors.filter(error => error.missing && !error.outputId).length
+ Math.max(missingOutputs, errors.filter(error => error.missing && error.outputId).length), errors };

View File

@ -7,7 +7,7 @@ import path from 'node:path';
import test from 'node:test';
import { verifyDeliveryBundle } from '../scripts/verify-delivery-bundle.mjs';
async function fixture(t, fakeHeader = false) {
async function fixture(t, { fakeHeader = false, compact = false } = {}) {
const temporary = await fs.mkdtemp(path.join(os.tmpdir(), 'xiaoyi-delivery-'));
t.after(() => fs.rm(temporary, { recursive: true, force: true }));
const root = path.join(temporary, 'bundle');
@ -26,10 +26,19 @@ async function fixture(t, fakeHeader = false) {
await fs.writeFile(path.join(temporary, 'manifest.json'), JSON.stringify({ size: dimensions }));
execFileSync('tar', ['-a', '-cf', 'fixture.zip', 'manifest.json'], { cwd: temporary });
const zip = await fs.readFile(path.join(temporary, 'fixture.zip'));
await add('工程文件/项目.xiaoyi', '工程文件', JSON.stringify({
const checkpoint = `工程文件/项目 资源/${snapshot}`;
const project = {
version: 2, resources: '项目 资源', snapshot, projectManifest: { included: ['canvas.pcraft'] },
}));
await add(`工程文件/项目 资源/${snapshot}/canvas.pcraft`, '工程资源', zip);
};
if (compact) {
const context = `${checkpoint}/state-0001.json`;
project.projectManifest.included.push('context.json');
project.resourcePaths = { 'canvas.pcraft': '工程文件/主图.pcraft', 'context.json': context };
await add(context, '工程资源', '{}');
} else {
await add(`${checkpoint}/canvas.pcraft`, '工程资源', zip);
}
await add('工程文件/项目.xiaoyi', '工程文件', JSON.stringify(project));
await add('工程文件/主图.pcraft', '工程文件', zip);
const psd = Buffer.alloc(26);
psd.write('8BPS');
@ -54,6 +63,12 @@ test('verifies the selected output and reports JPG dimensions', async t => {
assert.deepEqual(report.files.at(-1), { relativePath: '主图/主图-01.jpg', sizeBytes: 17, width: 1, height: 1 });
});
test('verifies a project whose canvas is the published PCraft', async t => {
const report = await verifyDeliveryBundle(await fixture(t, { compact: true }), ['main_images']);
assert.equal(report.ok, true, JSON.stringify(report.errors));
assert.equal(report.files.filter(row => row.relativePath.endsWith('.pcraft')).length, 1);
});
test('reports files missing from disk', async t => {
const root = await fixture(t);
await fs.unlink(path.join(root, 'PSD/主图.psb'));
@ -63,7 +78,7 @@ test('reports files missing from disk', async t => {
});
test('rejects a fake JPG header even when the digest matches', async t => {
const report = await verifyDeliveryBundle(await fixture(t, true));
const report = await verifyDeliveryBundle(await fixture(t, { fakeHeader: true }));
assert.equal(report.ok, false);
assert.match(report.errors[0].message, /JPG 文件头/);
});
@ -92,3 +107,31 @@ test('reports unlisted files in the bundle root and project resources', async t
assert.equal(report.ok, false);
assert.deepEqual(report.errors.map(error => error.path).sort(), ['debug.json', '工程文件/项目 资源/preview.png']);
});
test('checks disk path lengths and duplicate large files using verified digests', async t => {
const root = await fixture(t);
const manifestPath = path.join(root, '交付清单.json');
const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
const bytes = Buffer.alloc(10 * 1024 * 1024, 42);
const sha256 = createHash('sha256').update(bytes).digest('hex');
const names = ['x'.repeat(112) + '.png', 'duplicate.png'];
for (const name of names) {
const relativePath = '采用图/' + name;
await fs.mkdir(path.join(root, '采用图'), { recursive: true });
await fs.writeFile(path.join(root, relativePath), bytes);
manifest.files.push({ relativePath, category: '采用图', format: 'png',
sizeBytes: bytes.length, sha256, verified: true });
}
manifest.counts['采用图'] = names.length;
await fs.writeFile(manifestPath, JSON.stringify(manifest));
const report = await verifyDeliveryBundle(root);
assert.equal(report.ok, false);
assert.equal(report.longestRelativePath, '采用图/' + names[0]);
assert.equal(report.longestRelativePathLength, 120);
assert.deepEqual(report.duplicateLargeFiles, [names.map(name => '采用图/' + name)]);
assert.equal(report.failedCount, 1);
await fs.writeFile(path.join(root, '采用图', 'y'.repeat(113) + '.png'), 'x');
const tooLong = await verifyDeliveryBundle(root);
assert.equal(tooLong.longestRelativePathLength, 121);
assert.ok(tooLong.errors.some(error => error.message === '相对路径超过 120 字符'));
});

View File

@ -122,14 +122,9 @@ fn load_draft(project: &Path, file: &Path) -> photocraft_format::Result<Document
photocraft_format::load_draft(file, &draft_objects(project))
}
struct PortableDraft {
checkpoint: Vec<u8>,
archive: Vec<u8>,
}
fn portable_draft(project: &Path, file: &Path, target: &Path) -> R<Option<PortableDraft>> {
fn portable_draft(project: &Path, file: &Path, target: &Path) -> R<bool> {
if !photocraft_format::is_draft_file(file).map_err(|_| "工程画布文件无法读取")? {
return Ok(None);
return Ok(false);
}
let bytes = photocraft_format::read_file(file).map_err(|_| "工程画布文件无法读取")?;
transfer::check_pcraft(&bytes)?;
@ -137,7 +132,7 @@ fn portable_draft(project: &Path, file: &Path, target: &Path) -> R<Option<Portab
.map_err(|error| format!("工程画布对象无法打包:{error}"))?;
fs::create_dir_all(target.parent().ok_or("工程画布路径无效")?).map_err(|_| "工程画布目录无法创建")?;
photocraft_format::atomic_write(target, &portable).map_err(|_| "工程画布无法写入")?;
Ok(Some(PortableDraft { checkpoint: bytes, archive: portable }))
Ok(true)
}
/// Opt-in, local SDK transport. The personal Key never leaves this native process.

View File

@ -14,7 +14,7 @@ fn disk(error: std::io::Error) -> String {
}
fn name_component(name: &str) -> String {
let cleaned: String = name.chars().take(70).map(|ch| if ch.is_control() || "<>:\"/\\|?*".contains(ch) { '_' } else { ch }).collect();
let cleaned: String = name.chars().take(24).map(|ch| if ch.is_control() || "<>:\"/\\|?*".contains(ch) { '_' } else { ch }).collect();
let name = cleaned.trim_matches(|ch: char| ch == '.' || ch.is_whitespace());
let stem = name.split('.').next().unwrap_or_default().to_ascii_uppercase();
if name.is_empty() {
@ -145,22 +145,80 @@ pub(super) fn copy_generation(root: &Path, project: &Path, input: &Value, output
let mut adopted = Vec::new();
for (index, source) in data["imageSources"].as_array().into_iter().flatten().enumerate() {
let bytes = super::template_slots::candidate_pixels(project, &source["candidateArtifact"])?;
let parent = root.join("采用图").join(folder).join(label);
fs::create_dir_all(&parent).map_err(disk)?;
let path = parent.join(format!("{:02}.png", index + 1));
fs::write(&path, &bytes).map_err(disk)?;
let size = artifact_size(&path, "png")?;
let file = file_record(root, &path, "采用图", size)?;
let digest = &source["candidateArtifact"]["sha256"];
let existing = files.iter().find(|file| file["category"] == "采用图" && file["sha256"] == *digest);
let relative = if let Some(file) = existing {
file["relativePath"].clone()
} else {
let parent = root.join("采用图").join(folder).join(label);
fs::create_dir_all(&parent).map_err(disk)?;
let path = parent.join(format!("{:02}.png", index + 1));
fs::write(&path, &bytes).map_err(disk)?;
let size = artifact_size(&path, "png")?;
let file = file_record(root, &path, "采用图", size)?;
let relative = file["relativePath"].clone();
files.push(file);
relative
};
adopted.push(json!({"pageId":source["pageId"],"fieldId":source["fieldId"],
"slotId":source["slotId"],"candidateId":source["candidateId"],"kind":source["kind"],"prompt":source["prompt"],
"requestId":source["requestId"],"relativePath":file["relativePath"],"sha256":file["sha256"]}));
files.push(file);
"requestId":source["requestId"],"relativePath":relative,"sha256":digest}));
}
Ok(json!({"variantId":variant,"outputId":component,"generationId":id,
"unverifiedCopy":data["unverifiedCopy"],"unverifiedFacts":data["unverifiedFacts"].as_array().map_or(&[][..], Vec::as_slice),
"adoptedImages":adopted,"fidelityReport":data["fidelityReport"],"reopenVerification":data["reopenVerification"]}))
}
// Keep the working filenames in the manifest. Opening the package restores
// them so canvas and slot loaders can use their usual project paths.
fn compact_resources(root: &Path, snapshot: &Path, package: &mut Value, files: &mut Vec<Value>) -> R<()> {
let mut stored = BTreeMap::new();
for row in files.iter() {
stored.insert(row["sha256"].as_str().unwrap().to_owned(), row["relativePath"].clone());
}
let included = package["projectManifest"]["included"].as_array().ok_or("工程资源清单缺失")?;
let mut paths = BTreeMap::new();
for (index, entry) in included.iter().enumerate() {
let logical = entry.as_str().ok_or("工程资源路径无效")?;
let source = snapshot.join(logical);
let format = source.extension().and_then(|ext| ext.to_str()).ok_or("工程资源格式缺失")?;
let digest = canvas_workspace::file_digest(&source).map_err(disk)?;
if let Some(existing) = stored.get(&digest) {
fs::remove_file(&source).map_err(disk)?;
paths.insert(logical.to_owned(), existing.clone());
continue;
}
let kind = logical.split_once('/').map_or("state", |(folder, _)| folder);
let destination = snapshot.join(format!("{kind}-{:04}.{format}", index + 1));
let size = artifact_size(&source, format)?;
fs::rename(&source, &destination).map_err(disk)?;
let relative = destination.strip_prefix(root).map_err(|_| "交付文件不在成品目录内")?.to_string_lossy().replace(std::path::MAIN_SEPARATOR, "/");
let record = json!({"category":"工程资源","relativePath":relative,"format":format,
"width":size.map(|(width, _)| width),"height":size.map(|(_, height)| height),
"sizeBytes":fs::metadata(&destination).map_err(disk)?.len(),"sha256":digest,"verified":true});
stored.insert(digest, record["relativePath"].clone());
paths.insert(logical.to_owned(), record["relativePath"].clone());
files.push(record);
}
prune_empty_resource_dirs(snapshot)?;
package["resourcePaths"] = json!(paths);
Ok(())
}
fn prune_empty_resource_dirs(dir: &Path) -> R<()> {
for entry in fs::read_dir(dir).map_err(disk)? {
let entry = entry.map_err(disk)?;
if entry.file_type().map_err(disk)?.is_dir() {
let child = entry.path();
prune_empty_resource_dirs(&child)?;
if fs::read_dir(&child).map_err(disk)?.next().is_none() {
fs::remove_dir(child).map_err(disk)?;
}
}
}
Ok(())
}
fn sync_tree(dir: &Path) -> R<()> {
for entry in fs::read_dir(dir).map_err(disk)? {
let entry = entry.map_err(disk)?;
@ -209,35 +267,10 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu
fs::create_dir(&package_root).map_err(disk)?;
let project_file = package_root.join(format!("{name}.xiaoyi"));
let mut package = json!({"version":2,"localId":policy.project,"scope":policy.scope,
"snapshot":Uuid::new_v4().to_string(),"sourceRoot":project,"resources":format!("{name} 资源")});
let portable_digests = project_file::write_project(project, &project_file, &mut package, policy, true)?;
let reopened = read_json(&project_file)?;
if reopened != package {
return Err("小壹工程清单读回不一致".into());
}
transfer::no_credentials(&reopened)?;
let snapshot = project_file::resource_checkpoint(&project_file, &reopened)?;
let doc = photocraft_format::load_path(&snapshot.join("canvas.pcraft")).map_err(|error| format!("无法重开小壹工程画布:{error}"))?;
let mut files = vec![file_record(root, &project_file, "工程文件", Some((doc.size.width, doc.size.height)))?];
for entry in reopened["projectManifest"]["included"].as_array().ok_or("工程资源清单缺失")? {
let relative = entry.as_str().ok_or("工程资源路径无效")?;
let file = snapshot.join(relative);
let format = file.extension().and_then(|extension| extension.to_str()).unwrap_or("");
let size = artifact_size(&file, format)?;
let record = file_record(root, &file, "工程资源", size)?;
// Context is normalized, and compact drafts are embedded before delivery.
if relative != "context.json" {
let source = canvas_workspace::file_digest(&project.join(relative)).map_err(disk)?;
let matches_source = match portable_digests.get(relative) {
Some(digests) => source == digests.checkpoint && record["sha256"] == digests.archive,
None => record["sha256"] == source,
};
if !matches_source {
return Err("工程资源与本机草稿内容不一致".into());
}
}
files.push(record);
}
"snapshot":Uuid::new_v4().to_string(),"sourceRoot":project,"resources":"资源"});
project_file::write_project(project, &project_file, &mut package, policy, true)?;
let snapshot = project_file::resource_checkpoint(&project_file, &package)?;
let mut files = Vec::new();
let variants: HashSet<_> = outputs.iter().filter_map(|output| output["variantId"].as_str()).collect();
let mut variant_folders = BTreeMap::new();
@ -266,6 +299,14 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu
}
output_evidence.push(evidence);
}
compact_resources(root, &snapshot, &mut package, &mut files)?;
let canvas = files.iter().find(|record| record["relativePath"] == package["resourcePaths"]["canvas.pcraft"])
.ok_or("工程画布未列入成品清单")?;
let size = canvas["width"].as_u64().zip(canvas["height"].as_u64())
.map(|(width, height)| (width as u32, height as u32));
write_json(&project_file, &package)?;
files.push(file_record(root, &project_file, "工程文件", size)?);
let total = input["total"].as_u64().ok_or("本轮计划输出数无效")?;
let missing_outputs = total.checked_sub(outputs.len() as u64).ok_or("本轮已导出数量超过计划")?;
let all_outputs_completed = missing_outputs == 0;
@ -413,6 +454,60 @@ mod tests {
(root, project, local, input)
}
#[test]
#[ignore = "requires a copied production project"]
fn offline_delivery_reopens_copied_production_project() {
let project = PathBuf::from(std::env::var_os("JIANSUN_DELIVERY_SOURCE").unwrap());
let workspace = PathBuf::from(std::env::var_os("JIANSUN_DELIVERY_TEST_ROOT").unwrap());
let scope = std::env::var("JIANSUN_DELIVERY_SCOPE").unwrap();
let local = project.file_name().unwrap().to_str().unwrap();
let policy = transfer::Policy { chat: false, scope: &scope, project: local };
let mut input = read_json(&project.join("production-run.json")).unwrap();
input["deliveryDir"] = json!(workspace.join("deliveries"));
let started = std::time::Instant::now();
let delivered = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap();
let bundle = Path::new(delivered["path"].as_str().unwrap());
eprintln!("交付目录:{},耗时 {:?}", bundle.display(), started.elapsed());
let clean = workspace.join("x".repeat(139 - workspace.to_string_lossy().encode_utf16().count()));
assert_eq!(clean.to_string_lossy().encode_utf16().count(), 140);
fs::create_dir_all(&clean).unwrap();
let catalog = clean.join("交付清单.json");
fs::copy(bundle.join("交付清单.json"), &catalog).unwrap();
let delivery = read_json(&catalog).unwrap();
let mut entry = None;
let mut outputs = 0;
for row in delivery["files"].as_array().unwrap() {
let relative = row["relativePath"].as_str().unwrap();
assert!(relative.encode_utf16().count() <= 120, "{relative}");
let path = clean.join(relative);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::copy(bundle.join(relative), &path).unwrap();
if row["format"] == "xiaoyi" {
entry = Some(path);
} else if row["category"] == "工程文件" && row["format"] == "pcraft" {
let doc = photocraft_format::load_path(&path).unwrap();
assert_eq!(json!(doc.size.width), row["width"]);
assert_eq!(json!(doc.size.height), row["height"]);
outputs += 1;
}
}
assert_eq!(outputs, 3);
let drafts = workspace.join("reopened");
assert_eq!(project_file::open(&entry.unwrap(), &drafts, &scope).unwrap(), local);
let restored = drafts.join(local);
let mut original = canvas_workspace::load(&project).unwrap();
project_file::rebase_paths(&mut original, &project, &restored);
let reopened = canvas_workspace::load(&restored).unwrap();
assert_eq!(reopened["mappings"], original["mappings"]);
assert_eq!(reopened["adoptions"], original["adoptions"]);
let path = restored.join("canvas.pcraft");
let mut doc = photocraft_format::load_path(&path).unwrap();
doc.name = "离线编辑回存".into();
photocraft_format::PcraftWriter::new()
.save_path(&doc, &path, &Default::default()).unwrap();
assert_eq!(photocraft_format::load_path(&path).unwrap().name, "离线编辑回存");
}
#[test]
fn delivery_preference_reopens_and_clears_without_revising_creation_inputs() {
let root = tempfile::tempdir().unwrap();
@ -463,10 +558,6 @@ mod tests {
"generationId":detail["generationId"],"fields":["S01-T01"]
}]));
assert_eq!(delivered["unverifiedCopy"], manifest["unverifiedCopy"]);
let asset = manifest["files"].as_array().unwrap().iter().find(|entry|
entry["category"] == "工程资源" && entry["relativePath"].as_str().unwrap().ends_with("/creation-assets/sample.png")
).unwrap();
assert_eq!((&asset["width"], &asset["height"]), (&json!(7), &json!(5)));
for entry in manifest["files"].as_array().unwrap() {
let path = final_dir.join(entry["relativePath"].as_str().unwrap());
assert!(path.is_file(), "{}", path.display());
@ -518,15 +609,15 @@ mod tests {
assert!(layered.metadata.psd_global_blocks.iter().any(|(_, key, bytes)|
key == b"lnk2" && bytes.len() == 1 << 20 && bytes.iter().all(|&byte| byte == 123)));
}
let packaged = clean.join("天青椅.xiaoyi");
fs::copy(final_dir.join("工程文件/天青椅.xiaoyi"), &packaged).unwrap();
let clean_snapshot = project_file::resource_checkpoint(&packaged, &resources).unwrap();
for entry in resources["projectManifest"]["included"].as_array().unwrap() {
let relative = entry.as_str().unwrap();
let destination = clean_snapshot.join(relative);
fs::create_dir_all(destination.parent().unwrap()).unwrap();
fs::copy(snapshot.join(relative), destination).unwrap();
for entry in manifest["files"].as_array().unwrap() {
let relative = entry["relativePath"].as_str().unwrap();
let target = clean.join(relative);
fs::create_dir_all(target.parent().unwrap()).unwrap();
fs::copy(final_dir.join(relative), target).unwrap();
}
let packaged = clean.join("工程文件/天青椅.xiaoyi");
let asset = resources["resourcePaths"]["creation-assets/sample.png"].as_str().unwrap();
assert!(clean.join(asset).is_file());
fs::rename(&project, root.path().join("hidden-source")).unwrap();
assert_eq!(project_file::open(&packaged, &clean.join("drafts"), "owner").unwrap(), local);
let reopened = photocraft_format::load_path(&clean.join("drafts").join(&local).join("canvas.pcraft")).unwrap();

View File

@ -1,19 +1,14 @@
//! A project file points to its sibling resource directory and its current checkpoint.
use super::{Document, Path, PathBuf, R, Uuid, Value, fs, json, read_json, write_json};
use super::transfer::{self, Policy};
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
#[derive(Default)]
struct Selection {
included: Vec<String>,
excluded: Vec<Value>,
portable_digests: HashMap<String, PortableDigests>,
}
pub(super) struct PortableDigests {
pub(super) checkpoint: String,
pub(super) archive: String,
}
const CONTEXT: &str = "context.json";
const EXTENSION: &str = "xiaoyi";
@ -110,7 +105,7 @@ fn copy_file(source: &Path, target: &Path, previous: Option<&Path>) -> R<()> {
}
fn checkpoint_file(project: &Path, source: &Path, output: &Path, logical: &str, previous: Option<&Path>,
mode: CheckpointCopy<'_>, chat: bool) -> R<Option<PortableDigests>> {
mode: CheckpointCopy<'_>, chat: bool) -> R<()> {
let reopen = match mode {
CheckpointCopy::Reopen(old, new) => Some((old, new)),
_ => None,
@ -146,14 +141,8 @@ fn checkpoint_file(project: &Path, source: &Path, output: &Path, logical: &str,
fs::write(output, bytes).map_err(disk)?;
} else {
if logical.ends_with(".pcraft") {
if reopen.is_none() && let Some(portable) = super::portable_draft(project, source, output)? {
return Ok(matches!(mode, CheckpointCopy::Deliver).then(|| {
use sha2::{Digest, Sha256};
PortableDigests {
checkpoint: format!("{:x}", Sha256::digest(&portable.checkpoint)),
archive: format!("{:x}", Sha256::digest(&portable.archive)),
}
}));
if reopen.is_none() && super::portable_draft(project, source, output)? {
return Ok(());
}
if reopen.is_some() && photocraft_format::is_draft_file(source).map_err(disk)? {
return Err("工程画布缺少内嵌对象,无法独立打开".into());
@ -162,7 +151,7 @@ fn checkpoint_file(project: &Path, source: &Path, output: &Path, logical: &str,
}
copy_file(source, output, previous)?;
}
Ok(None)
Ok(())
}
#[derive(Clone, Copy)]
@ -191,7 +180,7 @@ fn copy_project(
let relative = path.strip_prefix(root).map_err(disk)?;
let logical = relative.to_string_lossy().replace('\\', "/");
if logical == "draft-objects" { continue; }
if matches!(mode, CheckpointCopy::Deliver) && matches!(logical.as_str(), "product-exports" | "production-run.json") {
if matches!(mode, CheckpointCopy::Deliver) && matches!(logical.as_str(), "product-exports" | "production-run.json" | "agent" | "agent-binding.json") {
selection.excluded.push(transfer::exclusion(&logical, "outside_delivery_checkpoint"));
continue;
}
@ -214,10 +203,8 @@ fn copy_project(
}
let output = target.join(relative);
fs::create_dir_all(output.parent().ok_or("工程资源路径无效")?).map_err(disk)?;
if let Some(digest) = checkpoint_file(root, &path, &output, &logical,
previous.map(|p| p.join(relative)).as_deref(), mode, policy.chat)? {
selection.portable_digests.insert(logical.clone(), digest);
}
checkpoint_file(root, &path, &output, &logical,
previous.map(|p| p.join(relative)).as_deref(), mode, policy.chat)?;
selection.included.push(logical);
} else {
selection.excluded.push(transfer::exclusion(&logical, "outside_project_checkpoint"));
@ -226,7 +213,59 @@ fn copy_project(
Ok(())
}
pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, policy: &Policy<'_>, delivery: bool) -> R<HashMap<String, PortableDigests>> {
fn trim_candidate_history(stage: &Path, selection: &mut Selection) -> R<()> {
let workspace_path = stage.join("canvas-workspace.json");
if !workspace_path.is_file() {
return Ok(());
}
let mut workspace = read_json(&workspace_path)?;
let Some(index) = workspace.as_object_mut().and_then(|state| state.remove("candidates")) else {
return Ok(());
};
let index = index.as_array().ok_or("候选索引无效")?;
let jobs: HashSet<_> = selection.included.iter().filter_map(|path| {
path.strip_prefix("image-jobs/")?.split_once('/').map(|(id, _)| id.to_owned())
}).collect();
let mut kept = HashSet::new();
let mut pending = Vec::new();
let collect = |text: &str, kept: &mut HashSet<String>, pending: &mut Vec<String>| {
for id in text.split(|c: char| !c.is_ascii_alphanumeric() && c != '-') {
if jobs.contains(id) && kept.insert(id.to_owned()) {
pending.push(id.to_owned());
}
}
};
collect(&workspace.to_string(), &mut kept, &mut pending);
let mut metadata: HashMap<&str, Vec<&str>> = HashMap::new();
for path in &selection.included {
if !path.ends_with(".json") || path == "canvas-workspace.json" { continue; }
if let Some((id, _)) = path.strip_prefix("image-jobs/").and_then(|path| path.split_once('/')) {
metadata.entry(id).or_default().push(path);
} else {
collect(&fs::read_to_string(stage.join(path)).map_err(disk)?, &mut kept, &mut pending);
}
}
while let Some(id) = pending.pop() {
for path in metadata.get(id.as_str()).into_iter().flatten() {
collect(&fs::read_to_string(stage.join(path)).map_err(disk)?, &mut kept, &mut pending);
}
}
let filtered: Vec<_> = index.iter().filter(|id| id.as_str().is_some_and(|id| kept.contains(id))).collect();
workspace["candidates"] = json!(filtered);
write_json(&workspace_path, &workspace)?;
for id in jobs.difference(&kept) {
let path = format!("image-jobs/{id}");
fs::remove_dir_all(stage.join(&path)).map_err(disk)?;
selection.excluded.push(transfer::exclusion(&path, "unreferenced_delivery_candidate"));
}
selection.included.retain(|path| {
path.strip_prefix("image-jobs/").and_then(|path| path.split_once('/'))
.is_none_or(|(id, _)| kept.contains(id))
});
Ok(())
}
pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, policy: &Policy<'_>, delivery: bool) -> R<()> {
let checkpoint = resource_checkpoint(file, manifest)?;
let resource_dir = checkpoint.parent().ok_or("工程资源目录无效")?;
fs::create_dir_all(resource_dir).map_err(disk)?;
@ -238,6 +277,7 @@ pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, polic
let mut selection = Selection::default();
let mode = if delivery { CheckpointCopy::Deliver } else { CheckpointCopy::Save };
copy_project(dir, dir, stage.path(), previous.as_deref(), mode, policy, &mut selection)?;
if delivery { trim_candidate_history(stage.path(), &mut selection)?; }
if !["canvas.pcraft", CONTEXT].into_iter().all(|required| selection.included.iter().any(|path| path == required)) {
return Err("工程缺少必要的编辑数据,未写入工程包".into());
}
@ -252,7 +292,7 @@ pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, polic
return Err(error);
}
if let Some(previous) = &previous { retire_checkpoint(resource_dir, previous, &manifest["localId"]); }
Ok(selection.portable_digests)
Ok(())
}
fn retire_checkpoint(resource_dir: &Path, checkpoint: &Path, project: &Value) {
@ -318,7 +358,7 @@ pub(super) fn save(
Ok(result)
}
fn rebase_paths(value: &mut Value, old: &Path, new: &Path) {
pub(super) fn rebase_paths(value: &mut Value, old: &Path, new: &Path) {
match value {
Value::String(text) => {
if let Ok(relative) = Path::new(text).strip_prefix(old) {
@ -339,6 +379,11 @@ fn rebase_paths(value: &mut Value, old: &Path, new: &Path) {
}
}
fn normal_relative(path: &Path) -> bool {
path.components().next().is_some()
&& path.components().all(|part| matches!(part, std::path::Component::Normal(_)))
}
pub(super) fn open(file: &Path, projects: &Path, scope: &str) -> R<String> {
let file = project_path(file)?;
let manifest = read_json(&file)?;
@ -372,7 +417,27 @@ pub(super) fn open(file: &Path, projects: &Path, scope: &str) -> R<String> {
fs::create_dir_all(projects).map_err(disk)?;
let stage = tempfile::tempdir_in(projects).map_err(disk)?;
let mut selection = Selection::default();
copy_project(&resources, &resources, stage.path(), None, CheckpointCopy::Reopen(old, &destination), &policy, &mut selection)?;
let mode = CheckpointCopy::Reopen(old, &destination);
if let Some(sources) = manifest.get("resourcePaths") {
let included = manifest["projectManifest"]["included"].as_array().ok_or("工程资源清单缺失")?;
let bundle = file.parent().and_then(Path::parent).ok_or("成品路径无效")?;
for entry in included {
let logical = entry.as_str().ok_or("工程资源路径无效")?;
let relative = Path::new(logical);
if !project_entry(relative) || !normal_relative(relative) {
return Err("工程资源路径无效".into());
}
let path = sources[logical].as_str().map(Path::new).filter(|path| normal_relative(path))
.ok_or("交付资源路径无效")?;
let source = bundle.join(path);
let target = stage.path().join(relative);
fs::create_dir_all(target.parent().ok_or("工程资源路径无效")?).map_err(disk)?;
checkpoint_file(&resources, &source, &target, logical, None, mode, chat)?;
selection.included.push(logical.to_owned());
}
} else {
copy_project(&resources, &resources, stage.path(), None, mode, &policy, &mut selection)?;
}
if manifest["version"] == 2 {
let restored = policy.manifest(stage.path(), selection.included, selection.excluded)?;
if manifest["projectManifest"]["version"] != 1 || restored["included"] != manifest["projectManifest"]["included"]
@ -396,6 +461,38 @@ mod tests {
use super::*;
use photocraft_doc::{Affine, ColorMode, Layer, LayerContent, SampleType, Size, SmartContentsId, SmartObject, SmartSource, Surface};
#[test]
fn delivery_keeps_referenced_candidates_and_discards_the_unreferenced_pool() {
let root = tempfile::tempdir().unwrap();
let stage = root.path();
let applied = Uuid::new_v4().to_string();
let parent = Uuid::new_v4().to_string();
let unused = Uuid::new_v4().to_string();
let mut selection = Selection::default();
for (id, task) in [
(&applied, json!({"parentCandidateId":parent})),
(&parent, json!({})),
(&unused, json!({})),
] {
let dir = format!("image-jobs/{id}");
fs::create_dir_all(stage.join(&dir)).unwrap();
let path = format!("{dir}/task.json");
write_json(&stage.join(&path), &task).unwrap();
selection.included.push(path);
}
let workspace = stage.join("canvas-workspace.json");
write_json(&workspace, &json!({
"candidates":[applied,parent,unused],
"mappings":{"detail":{"candidateArtifact":{"path":format!("image-jobs/{applied}/generated.png")}}}
})).unwrap();
trim_candidate_history(stage, &mut selection).unwrap();
assert_eq!(read_json(&workspace).unwrap()["candidates"], json!([applied,parent]));
assert_eq!(selection.included.len(), 2);
assert!(!stage.join("image-jobs").join(unused).exists());
}
#[test]
fn saved_project_restores_layers_metadata_and_candidate_files_without_the_working_directory() {
let temp = tempfile::tempdir().unwrap();

View File

@ -208,7 +208,7 @@ fn collect_backup_sources(base: &Path, path: &Path, prefix: &str, files: &mut Ve
.map_err(|_| "工程画布对象无法读取")? {
return Err("项目附件超过1GiB,尚未同步".into());
}
let path = if super::portable_draft(base, path, &staged)?.is_some() { staged.as_path() } else { path };
let path = if super::portable_draft(base, path, &staged)? { staged.as_path() } else { path };
let (sha, size) = file_digest(path)?;
if total.saturating_add(size) > SESSION_FILES_LIMIT { return Err("项目附件超过1GiB,尚未同步".into()); }
*total = total.saturating_add(size);
@ -678,7 +678,7 @@ impl Backend {
let _stage_cleanup = SyncStage(stage.clone());
let canvas = stage.join("canvas.pcraft");
let local_canvas = dir.join("canvas.pcraft");
if super::portable_draft(&dir, &local_canvas, &canvas)?.is_none() {
if !super::portable_draft(&dir, &local_canvas, &canvas)? {
fs::copy(local_canvas, &canvas).map_err(|_| "本机工程快照无法准备")?;
}
let (canvas_sha, canvas_size) = file_digest(&canvas)?;