From 0fed4105551a65b0818611b3b0df24a33f5e1603 Mon Sep 17 00:00:00 2001 From: endercodezz Date: Fri, 6 Nov 2026 16:53:24 +0200 Subject: [PATCH] feat(tools): show what a mod.cpk changes with p3p-cpk diff Each file of a mod is added, changed or same against one or more base archives, by extracted content, so a stored copy of a compressed file counts as the same. Names match without regard to case and a match that differs in case is marked: how the game's CRI library matches names is not known yet. Verified on ULUS-10512: all of umd0.cpk against the image is 5,860 same; a mod of real game files with one edited is reported as expected. tools/cpk/check.py: 24/24 CLI tests, 150 damaged mods included. --- .agents/skills/p3p-modding-vfs/SKILL.md | 2 +- .claude/skills/p3p-modding-vfs/SKILL.md | 2 +- README.md | 4 +- docs/CURRENT_STATE.md | 7 ++ docs/VERIFICATION.md | 9 ++ tools/cpk/src/main.zig | 105 +++++++++++++++++++++++- tools/cpk/test_cli.py | 68 +++++++++++++++ 7 files changed, 193 insertions(+), 4 deletions(-) diff --git a/.agents/skills/p3p-modding-vfs/SKILL.md b/.agents/skills/p3p-modding-vfs/SKILL.md index 5a19f914..75027133 100644 --- a/.agents/skills/p3p-modding-vfs/SKILL.md +++ b/.agents/skills/p3p-modding-vfs/SKILL.md @@ -31,7 +31,7 @@ Do **not** assume all mods are purely asset replacements. For every modification - `p3p/p3p-patches/ULUS10512.ini` — Verified memory offsets for intro skip and mod loader string pointers. - `p3p/Persona-3-Portable-Mod-Menu/` — Field script hooks (`.flow` / `.bf`) and menu initialization. -- `tools/cpk/` — Our Zig CLI: lists and extracts a CPK from the ISO or a loose `mod.cpk`, which also checks that the archive is readable (`build/cpk/bin/p3p-cpk --help`). +- `tools/cpk/` — Our Zig CLI: lists and extracts a CPK from the ISO or a loose `mod.cpk`, which also checks that the archive is readable, and `diff` shows which game files a mod replaces (`build/cpk/bin/p3p-cpk --help`). - `tools/CriFsV2Lib/` — Modern C# library for reading and parsing CriWare CPK archives. - `tools/CriPakTools/` — C# CLI tool for unpacking and repacking CPK files with CRILAYLA compression. - `tools/AtlusFileSystemLibrary/` — Comprehensive library for Atlus PAC, BIN, GIM, and TMX containers. diff --git a/.claude/skills/p3p-modding-vfs/SKILL.md b/.claude/skills/p3p-modding-vfs/SKILL.md index 5a19f914..75027133 100644 --- a/.claude/skills/p3p-modding-vfs/SKILL.md +++ b/.claude/skills/p3p-modding-vfs/SKILL.md @@ -31,7 +31,7 @@ Do **not** assume all mods are purely asset replacements. For every modification - `p3p/p3p-patches/ULUS10512.ini` — Verified memory offsets for intro skip and mod loader string pointers. - `p3p/Persona-3-Portable-Mod-Menu/` — Field script hooks (`.flow` / `.bf`) and menu initialization. -- `tools/cpk/` — Our Zig CLI: lists and extracts a CPK from the ISO or a loose `mod.cpk`, which also checks that the archive is readable (`build/cpk/bin/p3p-cpk --help`). +- `tools/cpk/` — Our Zig CLI: lists and extracts a CPK from the ISO or a loose `mod.cpk`, which also checks that the archive is readable, and `diff` shows which game files a mod replaces (`build/cpk/bin/p3p-cpk --help`). - `tools/CriFsV2Lib/` — Modern C# library for reading and parsing CriWare CPK archives. - `tools/CriPakTools/` — C# CLI tool for unpacking and repacking CPK files with CRILAYLA compression. - `tools/AtlusFileSystemLibrary/` — Comprehensive library for Atlus PAC, BIN, GIM, and TMX containers. diff --git a/README.md b/README.md index db96afcf..817a50a6 100644 --- a/README.md +++ b/README.md @@ -373,14 +373,16 @@ python tools/cpk/check.py --download # alternatively download the pinne build/cpk/bin/p3p-cpk list game.iso /PSP_GAME/USRDIR/umd0.cpk .bmd build/cpk/bin/p3p-cpk list mods/mod.cpk build/cpk/bin/p3p-cpk extract game.iso /PSP_GAME/USRDIR/umd0.cpk data/battle .tmp/extract +build/cpk/bin/p3p-cpk diff mods/mod.cpk game.iso /PSP_GAME/USRDIR/umd0.cpk /PSP_GAME/USRDIR/umd1.cpk build/cpk/bin/p3p-cpk check-trace game.iso .tmp/io-trace.csv ms0:/PSP/P3P=.tmp/mods ``` - `list` prints directory and name, offset, stored and extracted size, and whether the file is CRILAYLA-compressed; the optional last argument is a case-insensitive substring of `dir/name`. An archive it can't read fully is an error, which makes it a quick check of a community `mod.cpk`. - `extract` writes files under their CPK directories and decompresses them. All output paths are checked before the first write: `..`, absolute paths and names that are unsafe on Windows stop the extraction. +- `diff` shows what a `mod.cpk` does to the game's archives: each of its files is `added`, `changed` or `same`, by extracted content, so a stored copy of a compressed file counts as the same. Names match without regard to case, and a match that differs in case is marked `case-differs`. - `check-trace` verifies `p3p_pc_bootstrap --io-trace`: each read of a `.cpk` must be metadata or lie inside one file with the same FNV-1a 64. -Exit codes: **0** success, **1** `check-trace` found differences, **2** usage/input/output error. On Windows use `p3p-cpk.exe`. Keep game files and extracts under `.tmp/`. +Exit codes: **0** success, **1** `check-trace` found differences or `diff` found a file added or changed, **2** usage/input/output error. On Windows use `p3p-cpk.exe`. Keep game files and extracts under `.tmp/`. ### Continuous integration and releases (GitHub Actions) diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index 247ac782..16d69b1a 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -2,6 +2,13 @@ This is the current source of truth, newest entries first. Evidence concerns ULUS-10512; each section says whether it was measured on the PC runner, in Azahar or on a real New 3DS. +## `p3p-cpk diff`: what a mod changes in the game's archives (#76, 2026-11-06) + +- `tools/cpk`: `diff ` or `diff ...` reports each file of the mod as `added`, `changed` or `same` by extracted content. It is the first step of #23: which files a fan translation replaces. +- [VERIFIED] `umd0.cpk` and `umd1.cpk` share no file name and have no names that differ only in case, so a mod can be compared with both at once. The numbers are in `docs/VERIFICATION.md`. +- [UNVERIFIED] How the game's CRI library matches names: the game reads CPK contents itself, not `core/src/vfs.cpp`. `diff` matches without regard to case and marks `case-differs`, so such a file may not load in the game. +- [UNVERIFIED] No real fan translation was compared yet: none is available locally. + ## CPK tool in Zig without .NET: `tools/cpk` (#65, 2026-11-06) - `tools/cpk` (Zig 0.17.1, host only, one 1.0 MiB executable on Windows): `list`, `extract` and `check-trace` for a CPK on the ISO or a loose `.cpk`. `experiments/cpk-check` stays as the independent oracle. The numbers are in `docs/VERIFICATION.md`. diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index 3f5feae0..6b405b24 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -6,6 +6,15 @@ Current execution and coverage measurements: [CURRENT_STATE.md](CURRENT_STATE.md --- +## `p3p-cpk diff` (#76, 2026-11-06) + +Local ULUS-10512 ISO, Windows, Zig 0.17.1 `-Doptimize=safe`: + +- [VERIFIED] All of `umd0.cpk` as the mod, against the image's `umd0.cpk` and `umd1.cpk`: `mod files=5860 added=0 changed=0 same=5860 case_differs=0 base files=6198`, exit 0, 6 s. Each file is extracted from both sides. +- [VERIFIED] A mod built from real game files, compared with both archives: `AICALC.TBL` stored uncompressed is `same` (compressed in the game); `battle_pack2.bin` with one byte flipped, same size, is `changed`; `v100001.afs` from `umd1.cpk` is `same`; a lower-case name is `same ... case-differs`; a new file is `added`. Exit 1. Against `umd0.cpk` alone the `umd1.cpk` file is `added`. +- [VERIFIED] The CriFsV2Lib sample CPK, written by another tool: 3 files `added`, exit 1. +- [VERIFIED] `python tools/cpk/check.py`: 24/24 CLI tests, including 150 damaged mods through `diff` (exit 0, 1 or 2, never a panic). + ## CPK host CLI (#65, 2026-11-06) Local ULUS-10512 ISO, Windows, Zig 0.17.1 `-Doptimize=safe`, oracle `experiments/cpk-check` (CriFsV2Lib): diff --git a/tools/cpk/src/main.zig b/tools/cpk/src/main.zig index a54e803b..f3eb1c05 100644 --- a/tools/cpk/src/main.zig +++ b/tools/cpk/src/main.zig @@ -8,16 +8,24 @@ const usage = \\ p3p-cpk list [substring] \\ p3p-cpk extract [substring] \\ p3p-cpk extract [substring] + \\ p3p-cpk diff + \\ p3p-cpk diff ... \\ p3p-cpk check-trace [prefix=hostdir ...] \\ p3p-cpk --help | --version \\list prints every file: dir/name, offset, stored and extracted size, compressed. \\extract writes files under their CPK directories, decompressing CRILAYLA. \\Every output path is checked before anything is written; `..`, absolute \\paths and names unsafe on Windows are refused. Bytes above ASCII become %XX. + \\diff prints what a mod does to the base archives, for each of its files: added, + \\changed or same, comparing extracted content, so a stored and a compressed copy + \\of the same bytes are the same. Names match without regard to case; a match + \\that differs in case is marked case-differs. With several base archives the + \\first that has a file wins. \\check-trace verifies the reads of p3p_pc_bootstrap --io-trace: each read of a \\.cpk must be metadata or lie in one file with the same FNV-1a 64. prefix=hostdir \\maps traced paths to host files, e.g. ms0:/PSP/P3P=.tmp/mods. - \\Exit: 0 success, 1 check-trace found differences, 2 usage/input/output error. + \\Exit: 0 success, 1 check-trace or diff found differences (for diff: a file added + \\or changed), 2 usage/input/output error. \\ ; @@ -134,6 +142,7 @@ fn dispatch(init: std.process.Init, writer: *std.Io.Writer, args: []const []cons const rest = args[2..]; if (std.mem.eql(u8, command, "list")) return archiveCommand(init, writer, rest, false); if (std.mem.eql(u8, command, "extract")) return archiveCommand(init, writer, rest, true); + if (std.mem.eql(u8, command, "diff")) return diffCommand(init, writer, rest); if (std.mem.eql(u8, command, "check-trace")) return checkTrace(init, writer, rest); return error.UnknownCommand; } @@ -209,6 +218,100 @@ fn extractFiles(init: std.process.Init, writer: *std.Io.Writer, source: cpk.Sour return 0; } +const BaseFile = struct { + file: cpk.File, + source: cpk.Source, +}; + +fn lowerKey(allocator: std.mem.Allocator, file: cpk.File) ![]u8 { + const key = try std.fmt.allocPrint(allocator, "{s}/{s}", .{ file.dir, file.name }); + for (key) |*byte| byte.* = std.ascii.toLower(byte.*); + return key; +} + +fn sameContent(allocator: std.mem.Allocator, mod_source: cpk.Source, mod: cpk.File, base: BaseFile) !bool { + // A size of 0 is a TOC without ExtractSize: only the data can tell. + if (mod.extract_size != 0 and base.file.extract_size != 0 and mod.extract_size != base.file.extract_size) return false; + const left = try cpk.extract(allocator, mod_source, mod); + defer allocator.free(left); + const right = try cpk.extract(allocator, base.source, base.file); + defer allocator.free(right); + return std.mem.eql(u8, left, right); +} + +fn diffCommand(init: std.process.Init, writer: *std.Io.Writer, args: []const []const u8) !u8 { + const allocator = init.gpa; + const io = init.io; + if (args.len < 2) return error.ExpectedModAndBase; + var mod: Container = undefined; + try mod.open(io, args[0]); + defer mod.file.close(io); + if (!mod.is_cpk) return error.ModIsNotCpk; + var base: Container = undefined; + try base.open(io, args[1]); + defer base.file.close(io); + const paths = args[2..]; + if (base.is_cpk and paths.len != 0) return error.TooManyArguments; + if (!base.is_cpk and paths.len == 0) return error.ExpectedCpkPathOnImage; + + var arena_state: std.heap.ArenaAllocator = .init(allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const views = try arena.alloc(View, @max(paths.len, 1)); + const archives = try arena.alloc(cpk.Archive, views.len); + var opened: usize = 0; + defer for (archives[0..opened]) |archive| archive.deinit(allocator); + var base_files: std.StringHashMapUnmanaged(BaseFile) = .empty; + defer base_files.deinit(allocator); + for (views, archives, 0..) |*view, *archive, index| { + view.* = base.view; + var size = base.size; + if (!base.is_cpk) { + const extent = try iso.find(allocator, base.view.source(base.size), paths[index]); + const end = std.math.add(u64, extent.offset, extent.size) catch return error.OutOfBounds; + if (end > base.size) return error.OutOfBounds; + view.base = extent.offset; + size = extent.size; + } + const source = view.source(size); + archive.* = try cpk.Archive.open(allocator, source); + opened += 1; + for (archive.files) |file| { + const slot = try base_files.getOrPut(allocator, try lowerKey(arena, file)); + if (!slot.found_existing) slot.value_ptr.* = .{ .file = file, .source = source }; + } + } + + const mod_source = mod.view.source(mod.size); + const archive = try cpk.Archive.open(allocator, mod_source); + defer archive.deinit(allocator); + var added: u64 = 0; + var changed: u64 = 0; + var same: u64 = 0; + var case_differs: u64 = 0; + for (archive.files) |file| { + const key = try lowerKey(allocator, file); + defer allocator.free(key); + const found = base_files.get(key) orelse { + added += 1; + try writer.print("added {s}/{s} extract=0x{X}\n", .{ file.dir, file.name, file.extract_size }); + continue; + }; + const exact = std.mem.eql(u8, file.dir, found.file.dir) and std.mem.eql(u8, file.name, found.file.name); + const mark: []const u8 = if (exact) "" else " case-differs"; + if (!exact) case_differs += 1; + if (try sameContent(allocator, mod_source, file, found)) { + same += 1; + try writer.print("same {s}/{s}{s}\n", .{ file.dir, file.name, mark }); + } else { + changed += 1; + try writer.print("changed {s}/{s} extract=0x{X} -> 0x{X}{s}\n", .{ file.dir, file.name, found.file.extract_size, file.extract_size, mark }); + } + } + try writer.print("mod files={d} added={d} changed={d} same={d} case_differs={d} base files={d}\n", .{ archive.files.len, added, changed, same, case_differs, base_files.count() }); + return if (added == 0 and changed == 0) 0 else 1; +} + const TracedCpk = struct { owned_file: ?std.Io.File, view: *View, diff --git a/tools/cpk/test_cli.py b/tools/cpk/test_cli.py index 112cbba8..86aa343b 100644 --- a/tools/cpk/test_cli.py +++ b/tools/cpk/test_cli.py @@ -313,6 +313,74 @@ def test_garbage_and_usage(self): self.assertEqual(run("--help").returncode, 0) self.assertIn("0.1.0", run("--version").stdout) + def diff_fixture(self, entries, name="mod.cpk"): + path = self.dir / name + path.write_bytes(cpk(entries)) + return path + + def test_diff_kinds(self): + base = self.diff_fixture(ENTRIES, "base.cpk") + changed = PLAIN[:-1] + b"X" + mod = self.diff_fixture([ + ("data/a", "plain.bin", changed, len(changed)), # same size, other bytes + ("data/a", "root2.txt", b"new", 3), + ("", "root.txt", b"hello!", 6), # size differs: no need to read + ("data/b", "packed.bin", ORIGINAL, len(ORIGINAL)), # stored copy of a compressed file + ]) + result = run("diff", mod, base) + self.assertEqual(result.returncode, 1, result.stderr) + lines = result.stdout.splitlines() + self.assertEqual(lines[0], "changed data/a/plain.bin extract=0x300 -> 0x300") + self.assertEqual(lines[1], "added data/a/root2.txt extract=0x3") + self.assertEqual(lines[2], "changed /root.txt extract=0x5 -> 0x6") + self.assertEqual(lines[3], "same data/b/packed.bin") + self.assertEqual(lines[4], "mod files=4 added=1 changed=2 same=1 case_differs=0 base files=4") + + def test_diff_nothing_changed(self): + base = self.diff_fixture(ENTRIES, "base.cpk") + mod = self.diff_fixture([("data/b", "packed.bin", COMPRESSED, len(ORIGINAL))]) + result = run("diff", mod, base) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_diff_case_is_marked(self): + base = self.diff_fixture(ENTRIES, "base.cpk") + mod = self.diff_fixture([("DATA/a", "PLAIN.bin", PLAIN, len(PLAIN))]) + result = run("diff", mod, base) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("same DATA/a/PLAIN.bin case-differs", result.stdout) + self.assertIn("case_differs=1", result.stdout) + + def test_diff_against_an_image_with_several_archives(self): + image = self.dir / "game.iso" + image.write_bytes(iso(cpk(ENTRIES))) + mod = self.diff_fixture([("data/a", "plain.bin", PLAIN, len(PLAIN))]) + result = run("diff", mod, image, "/PSP_GAME/GAME.CPK", "/PSP_GAME/GAME.CPK") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("base files=4", result.stdout) + + def test_diff_usage(self): + base = self.diff_fixture(ENTRIES, "base.cpk") + image = self.dir / "game.iso" + image.write_bytes(iso(cpk(ENTRIES))) + self.assert_clean_error(run("diff", base)) + self.assert_clean_error(run("diff", image, base)) + self.assert_clean_error(run("diff", base, base, "/x")) + self.assert_clean_error(run("diff", base, image)) + self.assert_clean_error(run("diff", base, image, "/PSP_GAME/NOPE.CPK")) + + def test_diff_mutated_mod_never_crashes(self): + base = self.diff_fixture(ENTRIES, "base.cpk") + data = cpk(ENTRIES) + rng = random.Random(66) + path = self.dir / "mutated.cpk" + for round_number in range(150): + mutated = bytearray(data) + for _ in range(rng.randrange(1, 9)): + mutated[rng.randrange(4, len(mutated))] = rng.choice((0, 1, 0x7F, 0x80, 0xFF, rng.randrange(256))) + path.write_bytes(mutated) + result = run("diff", path, base) + self.assertIn(result.returncode, (0, 1, 2), (round_number, result.stderr[-400:])) + def trace(self, rows): path = self.dir / "trace.csv" path.write_text("path,offset,size,fnv1a64,time_us\n" + "".join(f"{p},{o},{s},0x{h:016X},0\n" for p, o, s, h in rows))