fix(apple): join recognized keys from NIBArchive field maps (#2248)

* fix(apple): join recognized keys from NIBArchive field maps

inspect-asset-catalog returned no resource-key matches for a decoded
NIBArchive resource whose recognized image key is present in the archive. The
NIBArchive projection groups an object's decoded fields under the node's
nibValues attribute beside the class, label and ID it derives from the same
archive, while the AppKit keyed-archive parser flattens the same fields onto
the node. The catalog join read only the top level, so a recognized NSImageName
on a decoded resource produced no row, and the empty-catalog limitation still
claimed resource keys were reported as unmatched.

Read an archive object's fields from both shapes, and give the namespace one
owner by exporting NIB_VALUES_ATTRIBUTE from the projection that writes it.
The recognized-field set stays in the catalog analysis, which owns that
contract.

Verified with 5 focused catalog tests, check:fast and verify:test-discovery on
macOS arm64, and through the public CLI against the reported NIBArchive
fixture. The keyed-archive control keeps its existing row, and a NIBArchive
with only an unrecognized title still produces none. The ibtool-dependent
native hierarchy lane requires full Xcode and was unavailable here.

* fix(apple): normalize resource keys at the NIBArchive producer

Fold the complementary implementation from #2256 into the earlier #2248 proposal, retaining the original contribution history.

Co-authored-by: Thang Luu <76550342+thangldw@users.noreply.github.com>

* fix(apple): restrict catalog joins to parsed resource nodes

---------

Co-authored-by: 吴佳浩 <wujiahao@supremind.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
Co-authored-by: Thang Luu <76550342+thangldw@users.noreply.github.com>
This commit is contained in:
吴佳浩Alben
2026-10-13 02:26:34 +08:00
committed by GitHub
co-authored by Thang Luu 吴佳浩 morluto
parent 47a51b08f4
commit fd985dbc5b
5 changed files with 268 additions and 34 deletions
@@ -1,9 +1,11 @@
import { createHash } from "node:crypto";
import { mkdir, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { encodeNibArchiveFixture } from "./NibArchive.fixture.js";
import { ArtifactReaderFailure } from "../ArtifactReader.js";
import {
analyzeAppleAssetCatalogs,
@@ -22,6 +24,13 @@ describe("Apple asset catalog application workflow", () => {
imageName: "Toolbar",
title: "not-an-asset-key",
image: 42,
nibValues: {
title: "not-an-asset-key",
imageName: { value: "not-a-scalar" },
image: 42,
assetName: "",
nested: { NSImageName: "not-a-direct-field" },
},
},
evidence: [
{
@@ -34,8 +43,13 @@ describe("Apple asset catalog application workflow", () => {
id: "ib:Main.nib:object:3",
kind: "control",
name: "Toolbar",
attributes: { title: "not-an-asset-key" },
evidence: [],
attributes: { NSImageName: "Toolbar", imageName: "Toolbar" },
evidence: [
{
artifact_path: "Contents/Resources/Main.nib",
artifact_sha256: "d".repeat(64),
},
],
},
]),
).toEqual([
@@ -118,3 +132,77 @@ describe("Apple asset catalog application workflow", () => {
);
});
});
it.each([1, 2])(
"joins NIBArchive keys against %i supplied assetutil renditions",
async (count) => {
const bundle = await createTestTempDirectory("rea-asset-nib-join-");
const resources = join(bundle, "Contents", "Resources");
await mkdir(resources, { recursive: true });
const archive = encodeNibArchiveFixture({
classes: ["NSIBObjectData", "NSImageView", "NSImage", "NSString"],
objects: [
{ classIndex: 0, values: { NSRoot: { ref: 1 } } },
{ classIndex: 1, values: { image: { ref: 2 } } },
{ classIndex: 2, values: { NSImageName: { ref: 3 } } },
{ classIndex: 3, values: { "NS.bytes": "Toolbar" } },
],
});
await writeFile(join(resources, "Panel.nib"), archive);
await writeFile(join(resources, "Assets.car"), "inert catalog fixture");
// Supplied metadata tests the post-engine join; it does not establish native catalog validity.
const result = await analyzeAppleAssetCatalogs({
environment: {},
bundlePath: bundle,
targetSha256: "a".repeat(64),
runAssetUtil: () =>
Promise.resolve(
JSON.stringify(
Array.from({ length: count }, (_, index) => ({
Name: "Toolbar",
RenditionName: `toolbar-${String(index)}.png`,
})),
),
),
});
expect(result.resource_key_matches).toHaveLength(1);
expect(result.resource_key_matches[0]).toMatchObject({
field: "NSImageName",
key: "Toolbar",
status: count === 1 ? "matched" : "ambiguous",
source_path: "Contents/Resources/Panel.nib",
source_archive_sha256: createHash("sha256").update(archive).digest("hex"),
renditions: Array.from({ length: count }, (_, index) =>
expect.objectContaining({
record_index: index,
rendition_name: `toolbar-${String(index)}.png`,
}),
),
});
},
);
it("keeps recognized image fields on NIBArchive controls out of resource joins", async () => {
const bundle = await createTestTempDirectory("rea-asset-nib-control-");
const resources = join(bundle, "Contents", "Resources");
await mkdir(resources, { recursive: true });
await writeFile(
join(resources, "Panel.nib"),
encodeNibArchiveFixture({
classes: ["NSIBObjectData", "NSButton", "NSString"],
objects: [
{ classIndex: 0, values: { NSRoot: { ref: 1 } } },
{ classIndex: 1, values: { NSImageName: { ref: 2 } } },
{ classIndex: 2, values: { "NS.bytes": "Toolbar" } },
],
}),
);
await writeFile(join(resources, "Assets.car"), "inert catalog fixture");
const result = await analyzeAppleAssetCatalogs({
environment: {},
bundlePath: bundle,
targetSha256: "a".repeat(64),
runAssetUtil: () => Promise.resolve(JSON.stringify([{ Name: "Toolbar" }])),
});
expect(result.resource_key_matches).toEqual([]);
});
@@ -8,6 +8,7 @@ import {
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
import {
appleAssetCatalogInputSchema,
appleResourceKeyFields,
parseAppleAssetCatalogRecords,
projectAppleAssetCatalogPage,
} from "../../domain/apple/appleAssetCatalog.js";
@@ -16,17 +17,6 @@ import { execFileOutput } from "../../process/ExecFileOutput.js";
const ASSETUTIL = "/usr/bin/assetutil";
const MAX_CATALOG_BYTES = 64 * 1024 * 1024;
const MAX_TOTAL_METADATA_BYTES = 64 * 1024 * 1024;
const RESOURCE_KEY_FIELDS = new Set([
"image",
"imageName",
"image_name",
"resourceName",
"resource_name",
"assetName",
"asset_name",
"UIImageName",
"NSImageName",
]);
/** Inspect compiled asset catalog metadata without extracting rendition bytes. */
export const analyzeAppleAssetCatalogs = async (input: {
@@ -201,27 +191,22 @@ export const collectInterfaceBuilderResourceKeys = (
}[],
) =>
nodes.flatMap((node) => {
if (node.kind !== "resource") return [];
const source = node.evidence.find(
(item) => item.artifact_path !== null && item.artifact_sha256 !== null,
);
const sourcePath = source?.artifact_path;
const sourceArchiveSha256 = source?.artifact_sha256;
if (sourcePath == null || sourceArchiveSha256 == null) return [];
return Object.entries(node.attributes).flatMap(([field, value]) =>
RESOURCE_KEY_FIELDS.has(field) &&
typeof value === "string" &&
value.length > 0
? [
{
sourceNodeId: node.id,
sourcePath,
sourceArchiveSha256,
field,
key: value,
},
]
: [],
);
return appleResourceKeyFields(node.attributes).flatMap(([field, value]) => [
{
sourceNodeId: node.id,
sourcePath,
sourceArchiveSha256,
field,
key: value,
},
]);
});
const runAssetUtil = async (
@@ -1,6 +1,7 @@
import { createHash } from "node:crypto";
import { parseBinary } from "plist";
import { appleResourceKeyFields } from "../../domain/apple/appleAssetCatalog.js";
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { projectPlistValue } from "../../domain/apple/plistValue.js";
import {
@@ -459,18 +460,27 @@ const projectNibArchive = (
break;
}
budget.reserveJsonStringOccurrence(name);
const nibValues = Object.fromEntries(
Object.entries(object.values).map(([key, value]) => {
budget.reserveJsonPropertyNameOccurrence(key);
return [key, dereference(value) ?? null];
}),
);
// Normalize only recognized scalar fields at the format owner. A keyed
// archive's authored nibValues dictionary must not gain this meaning.
const resourceFields = appleResourceKeyFields(nibValues);
for (const [field, value] of resourceFields) {
budget.reserveJsonPropertyNameOccurrence(field);
budget.reserveJsonStringOccurrence(value);
}
return [
String(object.id),
{
customClass: className,
label: name,
objectID: String(object.id),
nibValues: Object.fromEntries(
Object.entries(object.values).map(([key, value]) => {
budget.reserveJsonPropertyNameOccurrence(key);
return [key, dereference(value) ?? null];
}),
),
nibValues,
...Object.fromEntries(resourceFields),
},
];
}),
+23
View File
@@ -3,6 +3,29 @@ import { z } from "zod";
import { jsonValueSchema } from "../jsonValue.js";
import { AnalysisOutputError } from "../analysisErrorCore.js";
const RESOURCE_KEY_FIELDS = new Set([
"image",
"imageName",
"image_name",
"resourceName",
"resource_name",
"assetName",
"asset_name",
"UIImageName",
"NSImageName",
]);
/** Recognized direct scalar resource fields; nested dictionaries are not inferred. */
export const appleResourceKeyFields = (
attributes: Readonly<Record<string, unknown>>,
): [string, string][] =>
Object.entries(attributes).filter(
(entry): entry is [string, string] =>
RESOURCE_KEY_FIELDS.has(entry[0]) &&
typeof entry[1] === "string" &&
entry[1].length > 0,
);
/** Caller-controlled page bounds for compiled Apple asset metadata. */
export const appleAssetCatalogInputSchema = z.strictObject({
offset: z.number().int().min(0).default(0),
@@ -0,0 +1,128 @@
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { buildBinary } from "plist";
import { encodeNibArchiveFixture } from "../../../src/artifacts/apple/NibArchive.fixture.js";
import { appleAssetCatalogResultSchema } from "../../../src/domain/apple/appleAssetCatalog.js";
import { interfaceBuilderAnalysisSchema } from "../../../src/domain/apple/interfaceBuilderGraph.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
// Exact rooted NIBArchive bytes from #2176; inert parser fixture, not ibtool output.
const reportedArchive = Buffer.from(
"TklCQXJjaGl2ZQEAAAAKAAAABAAAADIAAAAEAAAAPgAAAAQAAABgAAAABAAAAHwAAACAgIGBgYGCgoGDg4GGTlNSb290hWltYWdli05TSW1hZ2VOYW1liE5TLmJ5dGVzgAoBAAAAgQoCAAAAggoDAAAAgwiHVG9vbGJhco6ATlNJQk9iamVjdERhdGGLgE5TSW1hZ2VWaWV3h4BOU0ltYWdliIBOU1N0cmluZw==",
"base64",
);
const resourceArchive = (field: string) =>
encodeNibArchiveFixture({
classes: ["NSIBObjectData", "NSImageView", "NSImage", "NSString"],
objects: [
{ classIndex: 0, values: { NSRoot: { ref: 1 } } },
{ classIndex: 1, values: { image: { ref: 2 } } },
{ classIndex: 2, values: { [field]: { ref: 3 } } },
{ classIndex: 3, values: { "NS.bytes": "Toolbar" } },
],
});
const keyedArchive = (nested: boolean) =>
buildBinary({
$archiver: "NSKeyedArchiver",
$version: 100000,
$top: { root: { UID: 1 } },
$objects: [
"$null",
{
$class: { UID: 2 },
...(nested
? { nibValues: { NSImageName: "Toolbar" } }
: { NSImageName: "Toolbar" }),
},
{ $classname: "NSImage", $classes: ["NSImage", "NSObject"] },
],
});
cliTest.skipIf(process.platform !== "darwin")(
"retains recognized NIBArchive resource keys and provenance through CLI and MCP without a catalog",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-asset-resource-keys-");
const { call } = await connectLocalToolsMcp();
for (const [name, field, archive, recognized] of [
["reported", "NSImageName", reportedArchive, true],
["alias", "imageName", resourceArchive("imageName"), true],
["title", "title", resourceArchive("title"), false],
["keyed-direct", "NSImageName", keyedArchive(false), true],
["keyed-nested", "NSImageName", keyedArchive(true), false],
] as const) {
const app = join(root, `${name}.app`);
const contents = join(app, "Contents");
await mkdir(join(contents, "Resources"), { recursive: true });
await mkdir(join(contents, "MacOS"));
const mach = Buffer.alloc(32);
mach.writeUInt32LE(0xfeedfacf, 0);
mach.writeUInt32LE(0x0100000c, 4);
mach.writeUInt32LE(2, 12);
await writeFile(join(contents, "MacOS", "App"), mach);
await writeFile(
join(contents, "Info.plist"),
"<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
);
await writeFile(join(contents, "Resources", "Panel.nib"), archive);
const decoded = await cli.run({
arguments: ["decode-interface-builder", app, "--json"],
});
expect(decoded.exitCode, decoded.stderr).toBe(0);
const graph = interfaceBuilderAnalysisSchema.parse(
parseEvidence(decoded.json).normalized_result,
).graph;
expect(graph.truncated).toBe(false);
const resource = graph.nodes.find(
(node) =>
node.kind === "resource" && node.attributes.class_name === "NSImage",
);
expect(
name === "keyed-direct"
? resource?.attributes
: resource?.attributes.nibValues,
).toMatchObject({
[field]: "Toolbar",
});
const inspected = await cli.run({
arguments: ["inspect-asset-catalog", app, "--json"],
});
expect(inspected.exitCode, inspected.stderr).toBe(0);
const result = appleAssetCatalogResultSchema.parse(
parseEvidence(inspected.json).normalized_result,
);
expect(result.catalogs).toEqual([]);
expect(result.resource_key_matches).toEqual(
!recognized
? []
: [
{
source_node_id: resource?.id,
source_path: "Contents/Resources/Panel.nib",
source_archive_sha256: createHash("sha256")
.update(archive)
.digest("hex"),
field,
key: "Toolbar",
status: "unmatched",
renditions: [],
},
],
);
const opened = await call("open_binary", { path: app });
expect(opened.isError).not.toBe(true);
const mcp = await call("inspect_asset_catalog", {});
expect(mcp.isError).not.toBe(true);
expect(parseEvidence(mcp.structuredContent).normalized_result).toEqual(
result,
);
}
},
30_000,
);