diff --git a/src/artifacts/apple/InterfaceBuilderAnalysis.ts b/src/artifacts/apple/InterfaceBuilderAnalysis.ts index 975717176c..fcb876a2e5 100644 --- a/src/artifacts/apple/InterfaceBuilderAnalysis.ts +++ b/src/artifacts/apple/InterfaceBuilderAnalysis.ts @@ -269,9 +269,7 @@ const decodeInterfaceBuilderBundle = async ( documents.push({ relativePath: entry.path, archiveSha256: documentHash, - documentKind: entry.path.includes(".storyboardc/") - ? "storyboard_scene" - : "nib", + documentKind: entry.documentKind, raw, ...(numberLiterals === undefined ? {} : { numberLiterals }), ...(nib === null || nib.omitted === 0 @@ -366,6 +364,10 @@ const decodeInterfaceBuilderBundle = async ( return finalOutcome.value; }; +type InterfaceBuilderCandidate = ArtifactEntry & { + readonly documentKind: InterfaceBuilderDocumentInput["documentKind"]; +}; + /** Select lexically earliest document paths independent of host traversal order. */ const selectInterfaceBuilderCandidates = async ( reader: DirectoryArtifactReader, @@ -373,7 +375,7 @@ const selectInterfaceBuilderCandidates = async ( maximumDocuments: number, traversal: ArtifactTraversalObservation, ): Promise<{ - readonly selected: readonly ArtifactEntry[]; + readonly selected: readonly InterfaceBuilderCandidate[]; readonly omittedSamples: readonly ArtifactEntry[]; readonly symlinkSamples: readonly ArtifactEntry[]; readonly omitted: number; @@ -382,18 +384,18 @@ const selectInterfaceBuilderCandidates = async ( readonly unreportedOmitted: number; }> => { const capacity = maximumDocuments + MAX_REPORTED_OMITTED_ARCHIVES; - const candidates: ArtifactEntry[] = []; + const candidates: InterfaceBuilderCandidate[] = []; const symlinkSamples: ArtifactEntry[] = []; let symlinks = 0; let unclassifiedSymlinks = 0; let firstUnclassifiedSymlink: string | undefined; let total = 0; for await (const entry of traversal.entries(reader, signal)) { + if (entry.kind !== "file" && entry.kind !== "symlink") continue; + const normalizedPath = entry.path.toLowerCase(); + const isNib = normalizedPath.endsWith(".nib"); if (entry.kind === "symlink") { - if ( - isInterfaceBuilderArchive(entry.path) || - entry.path.toLowerCase().endsWith(".storyboardc") - ) { + if (isNib || normalizedPath.endsWith(".storyboardc")) { symlinks += 1; retainCandidate(symlinkSamples, entry, MAX_REPORTED_OMITTED_ARCHIVES); } else { @@ -402,10 +404,12 @@ const selectInterfaceBuilderCandidates = async ( } continue; } - if (entry.kind !== "file" || !isInterfaceBuilderArchive(entry.path)) - continue; + if (!isNib) continue; total += 1; - retainCandidate(candidates, entry, capacity); + const documentKind = normalizedPath.includes(".storyboardc/") + ? "storyboard_scene" + : "nib"; + retainCandidate(candidates, { ...entry, documentKind }, capacity); } if (unclassifiedSymlinks > 0) traversal.record({ @@ -430,9 +434,9 @@ const selectInterfaceBuilderCandidates = async ( }; /** Keep the earliest bounded path set; directory iteration order is host-defined. */ -const retainCandidate = ( - candidates: ArtifactEntry[], - entry: ArtifactEntry, +const retainCandidate = ( + candidates: Entry[], + entry: Entry, maximum: number, ): void => { let low = 0; @@ -534,36 +538,29 @@ const finalizeHierarchyCoverage = ( ...result.graph, coverage: [ ...result.graph.coverage.map((facet) => { - const omittedConnection = unresolvedConnections.get( - facet.facet.replace(/^connections:/u, ""), - ); const [kind, ...pathParts] = facet.facet.split(":"); - const source = ( - unexaminedSources.get(pathParts.join(":")) ?? [] - ).find((source) => - source.facets.some((affected) => affected === kind), - ); - if (source !== undefined) - return { - ...facet, - status: "partial" as const, - reason: facet.reason ?? source.reason, - }; - return facet.facet.startsWith("connections:") && - omittedConnection !== undefined - ? { - ...facet, - status: "partial" as const, - // A connection dropped by the limit is recoverable by raising - // it, so that cause keeps the reason the graph already named. - // Only a facet with no other cause reports the omission. - reason: facet.reason ?? "connection_unresolved", - omitted: - facet.omitted === null - ? null - : facet.omitted + omittedConnection, - } - : facet; + const path = pathParts.join(":"); + const source = unexaminedSources + .get(path) + ?.find((source) => + source.facets.some((affected) => affected === kind), + ); + const omittedConnections = + kind === "connections" + ? unresolvedConnections.get(path) + : undefined; + if (source === undefined && omittedConnections === undefined) + return facet; + return { + ...facet, + status: "partial" as const, + // A caller can recover a limit omission by raising that limit. + reason: facet.reason ?? source?.reason ?? "connection_unresolved", + omitted: + facet.omitted === null + ? null + : facet.omitted + (omittedConnections ?? 0), + }; }), { facet: "archive_decode", @@ -1035,11 +1032,6 @@ const projectNibArchive = ( }; }; -const isInterfaceBuilderArchive = (path: string): boolean => { - const lower = path.toLowerCase(); - return lower.endsWith(".nib") || lower.endsWith("/objects.nib"); -}; - const readEntry = async ( reader: DirectoryArtifactReader, entry: ArtifactEntry, diff --git a/tests/acceptance/applications/interfaceBuilderNibRelationships.test.ts b/tests/acceptance/applications/interfaceBuilderNibRelationships.test.ts index eef54885e8..d94ece3b0a 100644 --- a/tests/acceptance/applications/interfaceBuilderNibRelationships.test.ts +++ b/tests/acceptance/applications/interfaceBuilderNibRelationships.test.ts @@ -230,12 +230,86 @@ const cases: readonly { }, ]; -cliTest.for(cases)( - "preserves NIB relationship evidence through CLI and MCP: $name", - async ( - { objects, links, complete, registryDiagnostic, decodeRejected }, - { cli }, - ) => { +const expectArchiveRelationships = ( + report: ReturnType, + archives: readonly ((typeof cases)[number] & { file: string })[], +) => { + const objectsById = new Map( + report.graph.nodes + .filter( + ({ attributes }) => + typeof attributes.interface_builder_object_id === "string", + ) + .map((node) => [node.id, node]), + ); + const objectLinks = report.graph.edges.flatMap((edge) => { + const from = objectsById.get(edge.from); + const to = edge.to === null ? undefined : objectsById.get(edge.to); + if (edge.relation !== "contains" || from === undefined || to === undefined) + return []; + const archive = from.evidence[0]?.artifact_path; + expect(to.evidence[0]?.artifact_path).toBe(archive); + return [ + [ + archive, + from.attributes.interface_builder_object_id, + to.attributes.interface_builder_object_id, + ], + ]; + }); + expect(objectLinks).toEqual( + archives.flatMap(({ file, links }) => + links.map(([from, to]) => [`Contents/Resources/${file}`, from, to]), + ), + ); + + for (const { + file, + name, + objects, + decodeRejected, + registryDiagnostic, + } of archives) { + const path = `Contents/Resources/${file}`; + if (decodeRejected) + expect(report.limitations.join("\n"), name).toContain( + `${path}: NIBArchive object reference is outside the object table`, + ); + const documentObjects = [...objectsById.values()].filter( + ({ evidence }) => evidence[0]?.artifact_path === path, + ); + for (const [index, object] of objects.entries()) { + if ( + decodeRejected || + ![1, 4, 5, 6].includes(object.classIndex) || + Array.isArray(object.values) + ) + continue; + const node = documentObjects.find( + ({ attributes }) => + attributes.interface_builder_object_id === String(index), + ); + for (const [key, value] of Object.entries(object.values)) { + if (typeof value !== "object" || value === null || !("ref" in value)) + continue; + expect(node?.attributes.nibValues, name).toMatchObject({ + [key]: { objectID: String(value.ref) }, + }); + } + } + if (registryDiagnostic !== undefined) + expect( + report.limitations.some( + (line) => line.includes(path) && line.includes(registryDiagnostic), + ), + name, + ).toBe(true); + } +}; + +cliTest( + "preserves each NIB's relationship evidence through CLI and MCP", + async ({ cli }) => { const root = await createTestTempDirectory("rea-nib-relationships-"); const app = join(root, "Fixture.app"); const contents = join(app, "Contents"); @@ -250,75 +324,57 @@ cliTest.for(cases)( join(contents, "Info.plist"), build({ CFBundleExecutable: "Fixture" }), ); - await writeFile( - join(resources, "Main.nib"), - encodeNibArchiveFixture({ - classes: [ - "NSIBObjectData", - "NSView", - "NSArray", - "NSCustomObject", - "NSButtonCell", - "CustomButtonCell", - "NSTextFieldCell", - ], - objects, - }), - ); + const archives = cases.map((testCase, index) => ({ + ...testCase, + file: testCase.decodeRejected + ? "00-dangling.nib" + : `${String(index).padStart(2, "0")}.nib`, + })); + for (const { file, objects } of archives) + await writeFile( + join(resources, file), + encodeNibArchiveFixture({ + classes: [ + "NSIBObjectData", + "NSView", + "NSArray", + "NSCustomObject", + "NSButtonCell", + "CustomButtonCell", + "NSTextFieldCell", + ], + objects, + }), + ); const output = await cli.run({ arguments: ["decode-interface-builder", app, "--json"], environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" }, }); expect(output.exitCode, output.stdout + output.stderr).toBe(0); - if (output.json === null) - throw new Error( - `CLI returned no JSON: ${output.stdout} ${output.stderr}`, - ); const report = interfaceBuilderAnalysisSchema.parse( parseEvidence(output.json).normalized_result, ); - if (decodeRejected) { - expect(report.documents).toEqual([]); - expect(report.graph.coverage).toContainEqual( - expect.objectContaining({ facet: "archive_decode", status: "partial" }), - ); - } else expect(report.documents[0]?.hierarchy_complete).toBe(complete); - const objectId = (id: string | null) => - id === null - ? undefined - : report.graph.nodes.find((node) => node.id === id)?.attributes - .interface_builder_object_id; - const objectLinks = report.graph.edges.flatMap((edge) => { - const from = objectId(edge.from); - const to = objectId(edge.to); - return edge.relation === "contains" && - typeof from === "string" && - typeof to === "string" - ? [[from, to]] - : []; - }); - expect(objectLinks).toEqual(links); - for (const [index, object] of objects.entries()) { - if ( - decodeRejected || - ![1, 4, 5, 6].includes(object.classIndex) || - Array.isArray(object.values) - ) - continue; - const node = report.graph.nodes.find( - ({ attributes }) => - attributes.interface_builder_object_id === String(index), - ); - for (const [key, value] of Object.entries(object.values)) { - if (typeof value !== "object" || value === null || !("ref" in value)) - continue; - expect(node?.attributes.nibValues).toMatchObject({ - [key]: { objectID: String(value.ref) }, - }); - } - } - if (registryDiagnostic !== undefined) - expect(report.limitations.join("\n")).toContain(registryDiagnostic); + expect( + report.documents.map(({ relative_path, hierarchy_complete }) => [ + relative_path, + hierarchy_complete, + ]), + ).toEqual( + archives + .filter(({ decodeRejected }) => !decodeRejected) + .map(({ file, complete }) => [`Contents/Resources/${file}`, complete]), + ); + expect(report.graph.coverage).toContainEqual( + expect.objectContaining({ + facet: "archive_decode", + status: "partial", + reason: "one_or_more_archives_invalid", + examined: archives.length, + }), + ); + + expectArchiveRelationships(report, archives); + const mcp = createTestMcp(); onTestFinished(async () => mcp.close()); const client = await openBundleResourcesTarget(mcp, onTestFinished, app); @@ -332,5 +388,17 @@ cliTest.for(cases)( parseEvidence(result.structuredContent).normalized_result, ), ).toEqual(report); + const rejectedOnly = await client.callTool({ + name: "decode_interface_builder", + arguments: { max_documents: 1 }, + }); + expect(rejectedOnly.isError, JSON.stringify(rejectedOnly)).not.toBe(true); + const rejected = interfaceBuilderAnalysisSchema.parse( + parseEvidence(rejectedOnly.structuredContent).normalized_result, + ); + expect(rejected.documents).toEqual([]); + expect(rejected.limitations.join("\n")).toContain( + "Contents/Resources/00-dangling.nib: NIBArchive object reference is outside the object table", + ); }, ); diff --git a/tests/boundary/filesystem/interfaceBuilderBundle.test.ts b/tests/boundary/filesystem/interfaceBuilderBundle.test.ts index 817081d8f4..cb2865d0d4 100644 --- a/tests/boundary/filesystem/interfaceBuilderBundle.test.ts +++ b/tests/boundary/filesystem/interfaceBuilderBundle.test.ts @@ -2,7 +2,7 @@ import { createVerifierCommands } from "../../../scripts/lib/verify-commands.mjs import { withVerifierCleanup } from "../../../scripts/lib/verifier-cleanup.mjs"; import { binaryKeyedArchiveUidShapes } from "../../fixtures/keyedArchiveUidShapes.js"; import { mkdir, symlink, writeFile } from "node:fs/promises"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { buildBinary } from "plist"; import { describe, expect, it, onTestFinished, vi } from "vitest"; @@ -667,7 +667,7 @@ describe("keyed archive hierarchy coverage", () => { }); describe("compiled Interface Builder bundle reader cancellation", () => { - it("honors cancellation during directory traversal", async () => { + it("honors cancellation before directory traversal", async () => { const root = await createTestTempDirectory("rea-ib-test-"); const controller = new AbortController(); controller.abort(); @@ -704,7 +704,13 @@ describe("flat Interface Builder plist values", () => { ); await writeFile( join(resources, "Xml.nib"), - '$archiverNSKeyedArchiver$objects$nullNSWhiteMC41AA==NSDate2026-10-07T00:00:00Z$top', + ` + com.apple.ibtool.document.objectscell + classNSView + NSWhiteMC41AA== + NSDate2026-10-07T00:00:00Z + + `, ); const analysis = await analyzeInterfaceBuilderBundle({ @@ -721,7 +727,24 @@ describe("flat Interface Builder plist values", () => { expect(analysis.graph.coverage).toContainEqual( expect.objectContaining({ facet: "archive_decode", status: "complete" }), ); - expect(analysis.graph.nodes.map(({ name }) => name)).toContain("Build"); + expect(analysis.graph.nodes).toContainEqual( + expect.objectContaining({ name: "Build" }), + ); + expect( + analysis.graph.nodes.find(({ name }) => name === "NSColor")?.attributes + .NSWhite, + ).toEqual({ + $plist_type: "data", + base64: "MC41AA==", + }); + expect( + analysis.graph.nodes.find( + ({ attributes }) => attributes.interface_builder_object_id === "cell", + )?.attributes, + ).toMatchObject({ + NSWhite: { $plist_type: "data", base64: "MC41AA==" }, + NSDate: { $plist_type: "date", iso8601: "2026-10-07T00:00:00.000Z" }, + }); }); }); @@ -1530,15 +1553,6 @@ describe("Interface Builder XML plist depth", () => { "Contents/Resources/BeyondLimit.nib: omitted because aggregate decode budget exhausted.", ); }); - - it("restores released representation bytes up to the initial budget", () => { - const budget = new InterfaceBuilderDecodeBudget(100); - budget.reserve(60, "reserve"); - budget.release(60); - expect(budget.remainingBytes).toBe(100); - budget.release(10); - expect(budget.remainingBytes).toBe(100); - }); }); describe("bounded Interface Builder archive decoding", () => { @@ -1705,210 +1719,129 @@ describe("Xcode-compiled Interface Builder archives", () => { ); }); -describe("NIBArchive UIKit event connections", () => { - it("projects a runtime event connection and its event mask", async () => { - const root = await createTestTempDirectory("rea-ib-test-"); - const bundle = join(root, "Example.app"); - await mkdir(bundle, { recursive: true }); - await writeFile( - join(bundle, "Cell.nib"), - encodeNibArchiveFixture({ - classes: [ - "UIProxyObject", - "UIClassSwapper", - "UIButton", - "UIRuntimeEventConnection", - "NSString", - ], - objects: [ - { classIndex: 0, values: { UIProxiedObjectIdentifier: { ref: 5 } } }, - { classIndex: 1, values: { UIClassName: { ref: 6 } } }, - { classIndex: 2, values: {} }, - { - classIndex: 3, - values: { - UISource: { ref: 2 }, - UIDestination: { ref: 1 }, - UILabel: { ref: 7 }, - UIEventMask: 64, - }, - }, - { classIndex: 2, values: {} }, - { classIndex: 4, values: { "NS.bytes": "IBFilesOwner" } }, - { classIndex: 4, values: { "NS.bytes": "BuildCell" } }, - { classIndex: 4, values: { "NS.bytes": "buildTapped:" } }, - ], - }), - ); - - const analysis = await analyzeInterfaceBuilderBundle({ - bundlePath: bundle, - targetSha256: "e".repeat(64), - }); - const byId = new Map(analysis.graph.nodes.map((node) => [node.id, node])); - const named = (id: string | null) => - id === null ? null : (byId.get(id)?.name ?? null); - const action = analysis.graph.nodes.find(({ kind }) => kind === "action"); - expect(action).toMatchObject({ - name: "buildTapped:", - attributes: { ui_event_mask: 64 }, - }); - const actionEdges = analysis.graph.edges.filter( - ({ relation }) => relation === "target_action", - ); - expect( - actionEdges - .filter(({ to }) => to === action?.id) - .map(({ from }) => named(from)), - ).toEqual(["UIButton"]); - expect( - actionEdges - .filter(({ from }) => from === action?.id) - .map(({ to }) => named(to)), - ).toEqual(expect.arrayContaining(["BuildCell"])); - expect( - analysis.graph.nodes.find(({ name }) => name === "IBFilesOwner")?.kind, - ).toBe("placeholder"); - expect(analysis.graph.nodes.map(({ name }) => name)).not.toContain( +it("retains UIKit event routes and accounts for ownerless and limited connectors", async () => { + const bundlePath = await createTestTempDirectory("rea-ib-event-"); + const controller = { classIndex: 1, values: { UIClassName: { ref: 5 } } }; + const button = { classIndex: 2, values: {} }; + const ownerless = { + classIndex: 3, + values: { UIDestination: { ref: 1 }, UIEventMask: 64 }, + }; + const cell = encodeNibArchiveFixture({ + classes: [ + "UIProxyObject", + "UIClassSwapper", + "UIButton", "UIRuntimeEventConnection", - ); + "NSString", + ], + objects: [ + { classIndex: 0, values: { UIProxiedObjectIdentifier: { ref: 4 } } }, + controller, + button, + button, + { classIndex: 4, values: { "NS.bytes": "IBFilesOwner" } }, + { classIndex: 4, values: { "NS.bytes": "BuildCell" } }, + { classIndex: 4, values: { "NS.bytes": "buildTapped:" } }, + { + classIndex: 3, + values: { + UISource: { ref: 2 }, + UIDestination: { ref: 1 }, + UILabel: { ref: 6 }, + UIEventMask: 64, + }, + }, + { + classIndex: 3, + values: { + UISource: { ref: 3 }, + UIDestination: { ref: 1 }, + UILabel: { ref: 6 }, + }, + }, + ownerless, + ], }); + await writeFile(join(bundlePath, "Cell.nib"), cell); + await writeFile( + join(bundlePath, "Ownerless.nib"), + encodeNibArchiveFixture({ + classes: [ + "UIView", + "UIViewController", + "UIButton", + "UIRuntimeEventConnection", + ], + objects: [ + { classIndex: 0, values: {} }, + { classIndex: 1, values: {} }, + ownerless, + ], + }), + ); - it("reports a runtime connection with no resolvable owner as an omission", async () => { - const root = await createTestTempDirectory("rea-ib-ownerless-"); - const bundle = join(root, "Example.app"); - await mkdir(bundle, { recursive: true }); - // The connector is recognized by class, but carries no UISource reference, - // so no connection can be projected from it. - await writeFile( - join(bundle, "Cell.nib"), - encodeNibArchiveFixture({ - classes: [ - "UIProxyObject", - "UIClassSwapper", - "UIButton", - "UIRuntimeEventConnection", - "NSString", - ], - objects: [ - { classIndex: 0, values: { UIProxiedObjectIdentifier: { ref: 5 } } }, - { classIndex: 1, values: { UIClassName: { ref: 6 } } }, - { classIndex: 2, values: {} }, - { - classIndex: 3, - values: { UIDestination: { ref: 1 }, UIEventMask: 64 }, - }, - { classIndex: 2, values: {} }, - { classIndex: 4, values: { "NS.bytes": "IBFilesOwner" } }, - { classIndex: 4, values: { "NS.bytes": "BuildCell" } }, - ], - }), - ); - - const analysis = await analyzeInterfaceBuilderBundle({ - bundlePath: bundle, - targetSha256: "e".repeat(64), - }); - - expect(analysis.graph.coverage).toContainEqual( - expect.objectContaining({ - facet: "connections:Cell.nib", - status: "partial", - reason: "connection_unresolved", - examined: 0, - omitted: 1, - }), - ); - // The keyed-archive producer counts a recognized connector it cannot emit, - // so this producer has to report the same document total for the same - // connector rather than zero. - expect(analysis.documents).toContainEqual( - expect.objectContaining({ - relative_path: "Cell.nib", - connection_count: 1, - }), - ); - expect(analysis.graph.truncated).toBe(true); - expect(analysis.limitations).toContainEqual( - expect.stringMatching(/resolvable owner.*omissions/iu), - ); + const input = { bundlePath, targetSha256: "e".repeat(64) }; + const full = await analyzeInterfaceBuilderBundle(input); + const action = full.graph.nodes.find( + ({ kind, attributes }) => + kind === "action" && attributes.ui_event_mask === 64, + ); + expect(action?.name).toBe("buildTapped:"); + const named = (id: string | null) => + full.graph.nodes.find((node) => node.id === id)?.name; + const actions = full.graph.edges.filter( + ({ relation }) => relation === "target_action", + ); + expect( + actions + .filter(({ to }) => to === action?.id) + .map(({ from }) => named(from)), + ).toEqual(["UIButton"]); + expect( + actions + .filter(({ from }) => from === action?.id) + .map(({ to }) => named(to)), + ).toContain("BuildCell"); + expect( + full.graph.nodes.find(({ name }) => name === "IBFilesOwner")?.kind, + ).toBe("placeholder"); + expect(full.graph.nodes.map(({ name }) => name)).not.toContain( + "UIRuntimeEventConnection", + ); + expect( + full.documents.map(({ relative_path, connection_count }) => [ + relative_path, + connection_count, + ]), + ).toEqual([ + ["Cell.nib", 3], + ["Ownerless.nib", 1], + ]); + expect(full.graph.coverage).toContainEqual({ + facet: "connections:Ownerless.nib", + status: "partial", + reason: "connection_unresolved", + examined: 0, + omitted: 1, }); -}); + expect(full.graph.truncated).toBe(true); + expect(full.limitations).toContainEqual( + expect.stringMatching(/resolvable owner.*omissions/iu), + ); -describe("NIBArchive ownerless connector accounting", () => { - it("keeps a connection dropped by the limit reported as a limit", async () => { - const root = await createTestTempDirectory("rea-ib-ownerless-limit-"); - const bundle = join(root, "Example.app"); - await mkdir(bundle, { recursive: true }); - // Two resolvable connectors and one ownerless connector with the limit - // below the resolvable count, so this facet has both causes at once. Only a - // higher limit recovers the dropped connection, so that is the reason the - // caller needs, exactly as the keyed-archive producer reports it. - await writeFile( - join(bundle, "Cell.nib"), - encodeNibArchiveFixture({ - classes: [ - "UIProxyObject", - "UIClassSwapper", - "UIButton", - "UIRuntimeEventConnection", - "NSString", - ], - objects: [ - { classIndex: 0, values: { UIProxiedObjectIdentifier: { ref: 5 } } }, - { classIndex: 1, values: { UIClassName: { ref: 6 } } }, - { classIndex: 2, values: {} }, - { - classIndex: 3, - values: { - UISource: { ref: 2 }, - UIDestination: { ref: 1 }, - UILabel: { ref: 7 }, - UIEventMask: 64, - }, - }, - { classIndex: 2, values: {} }, - { classIndex: 4, values: { "NS.bytes": "IBFilesOwner" } }, - { classIndex: 4, values: { "NS.bytes": "BuildCell" } }, - { classIndex: 4, values: { "NS.bytes": "buildTapped:" } }, - { - classIndex: 3, - values: { - UISource: { ref: 4 }, - UIDestination: { ref: 1 }, - UILabel: { ref: 7 }, - }, - }, - { - classIndex: 3, - values: { UIDestination: { ref: 1 }, UIEventMask: 64 }, - }, - ], - }), - ); - - const analysis = await analyzeInterfaceBuilderBundle({ - bundlePath: bundle, - targetSha256: "e".repeat(64), - limits: { max_connections: 1 }, - }); - - expect(analysis.graph.coverage).toContainEqual( - expect.objectContaining({ - facet: "connections:Cell.nib", - status: "partial", - reason: "connection_limit_reached", - examined: 1, - omitted: 2, - }), - ); - expect(analysis.documents).toContainEqual( - expect.objectContaining({ - relative_path: "Cell.nib", - connection_count: 3, - }), - ); + const limited = await analyzeInterfaceBuilderBundle({ + ...input, + limits: { max_connections: 1 }, }); + expect(limited.graph.coverage).toContainEqual({ + facet: "connections:Cell.nib", + status: "partial", + reason: "connection_limit_reached", + examined: 1, + omitted: 2, + }); + expect(limited.documents[0]?.connection_count).toBe(3); }); describe("NIBArchive single-object connectors", () => { @@ -2119,23 +2052,6 @@ describe("NIBArchive connectors with unusable sources", () => { describe.skipIf(process.platform !== "darwin")( "Foundation Interface Builder XML encodings", () => { - it.each(interfaceBuilderEncodings)( - "filesystem preserves native %s graph and original bytes", - async (encoding) => { - const fixture = await createInterfaceBuilderEncodingFixture(encoding); - const result = await analyzeInterfaceBuilderBundle({ - bundlePath: fixture.app, - targetSha256: "e".repeat(64), - }); - expectInterfaceBuilderEncoding( - result, - fixture.expected, - fixture.bytes, - fixture.oracle, - ); - }, - ); - cliTest.for(interfaceBuilderEncodings)( "built CLI preserves native $0 graph and original bytes", async (encoding, { cli }) => { @@ -2160,18 +2076,6 @@ describe.skipIf(process.platform !== "darwin")( }, ); - it.each(invalidInterfaceBuilderEncodings)( - "filesystem rejects %s without graph substitution", - async (encoding) => { - const fixture = await createInterfaceBuilderEncodingFixture(encoding); - const result = await analyzeInterfaceBuilderBundle({ - bundlePath: fixture.app, - targetSha256: "e".repeat(64), - }); - expectInvalidInterfaceBuilderEncoding(result); - }, - ); - cliTest.for(invalidInterfaceBuilderEncodings)( "built CLI reports $0 as invalid archive bytes", async (encoding, { cli }) => { @@ -2193,28 +2097,48 @@ describe.skipIf(process.platform !== "darwin")( }, ); -it("reports a plain plist named nib as undecoded while retaining a valid empty archive", async () => { +it("reports invalid plain plists and classifies storyboard scenes without changing archive paths", async () => { const bundle = await createTestTempDirectory("rea-ib-archive-recognition-"); await writeFile( join(bundle, "Plain.nib"), buildBinary({ CFBundleIdentifier: "sample" }), ); - await writeFile( - join(bundle, "Empty.nib"), - buildBinary({ "com.apple.ibtool.document.objects": {} }), - ); + const valid = [ + ["Empty.nib", "nib", "scene"], + ["Lower.storyboardc/Scene.nib", "storyboard_scene", "storyboard"], + ["Upper.STORYBOARDC/Scene.NIB", "storyboard_scene", "storyboard"], + ] as const; + const emptyArchive = buildBinary({ "com.apple.ibtool.document.objects": {} }); + for (const [path] of valid) { + await mkdir(dirname(join(bundle, path)), { recursive: true }); + await writeFile(join(bundle, path), emptyArchive); + } const result = await analyzeInterfaceBuilderBundle({ bundlePath: bundle, targetSha256: "a".repeat(64), }); - expect(result.documents.map(({ relative_path }) => relative_path)).toEqual([ - "Empty.nib", - ]); + expect( + result.documents.map(({ relative_path, document_kind }) => [ + relative_path, + document_kind, + ]), + ).toEqual(valid.map(([path, kind]) => [path, kind])); + expect(result.graph.nodes).toEqual( + expect.arrayContaining( + valid.map(([path, kind, nodeKind]) => + expect.objectContaining({ + name: path, + kind: nodeKind, + attributes: { document_kind: kind }, + }), + ), + ), + ); expect( result.graph.coverage.find(({ facet }) => facet === "archive_decode"), ).toMatchObject({ status: "partial", - examined: 2, + examined: 4, reason: "one_or_more_archives_invalid", }); }); @@ -2237,20 +2161,43 @@ it("preserves authored binary UID-shaped dictionaries through UI archive decodin }); }); -it.each(["embedded", "segue", "neither"] as const)( +it.each([ + ["embedded", "embedded_nib_archive_not_decoded", false], + ["segue", "storyboard_segue_template_not_decoded", false], + ["neither", null, false], + [ + "embedded with ownerless connector", + "embedded_nib_archive_not_decoded", + true, + ], +] as const)( "reports recognized unexamined nib source coverage: %s", - async (source) => { + async (source, reason, ownerless) => { + const embedded = reason === "embedded_nib_archive_not_decoded"; const bundle = await createTestTempDirectory("rea-ui-unexamined-sources-"); await writeFile( join(bundle, "Main.nib"), encodeNibArchiveFixture({ - classes: ["UINib", "UIStoryboardShowSegueTemplate", "NSView"], + classes: [ + "UINib", + "UIStoryboardShowSegueTemplate", + "NSView", + "UIRuntimeEventConnection", + ], objects: [ { classIndex: 2, values: {} }, - ...(source === "embedded" + ...(embedded ? [{ classIndex: 0, values: { "UINib.archiveData": { ref: 0 } } }] : []), ...(source === "segue" ? [{ classIndex: 1, values: {} }] : []), + ...(ownerless + ? [ + { + classIndex: 3, + values: { UIDestination: { ref: 0 }, UIEventMask: 64 }, + }, + ] + : []), ], }), ); @@ -2262,23 +2209,36 @@ it.each(["embedded", "segue", "neither"] as const)( expect( result.graph.coverage.find(({ facet }) => facet === `${kind}:Main.nib`) ?.status, - ).toBe(source === "embedded" ? "partial" : "complete"); + ).toBe(embedded ? "partial" : "complete"); expect( result.graph.coverage.find( ({ facet }) => facet === "connections:Main.nib", - )?.status, - ).toBe(source === "neither" ? "complete" : "partial"); - expect( - result.graph.coverage.find(({ facet }) => facet === "archive_decode") - ?.status, - ).toBe(source === "neither" ? "complete" : "partial"); + ), + ).toMatchObject({ + status: source === "neither" ? "complete" : "partial", + reason, + examined: 0, + omitted: ownerless ? 1 : 0, + }); + expect(result.documents[0]?.connection_count).toBe(ownerless ? 1 : 0); + for (const [facet, partial] of [ + ["archive_decode", reason !== null], + ["archive_object_decode", embedded], + ] as const) { + expect( + result.graph.coverage.find((row) => row.facet === facet), + ).toMatchObject({ + status: partial ? "partial" : "complete", + reason: partial ? "serialized_archive_content_unexamined" : null, + examined: 1, + omitted: 0, + }); + } if (source !== "neither") { expect(result.graph.truncated).toBe(true); expect(result.limitations).toContainEqual( expect.stringContaining( - source === "embedded" - ? "embedded archive data" - : "segue template object", + embedded ? "embedded archive data" : "segue template object", ), ); } diff --git a/tests/boundary/mcp/interfaceBuilderSummaryMcp.test.ts b/tests/boundary/mcp/interfaceBuilderSummaryMcp.test.ts index 6a0cd51a20..adecd79253 100644 --- a/tests/boundary/mcp/interfaceBuilderSummaryMcp.test.ts +++ b/tests/boundary/mcp/interfaceBuilderSummaryMcp.test.ts @@ -126,7 +126,10 @@ mcpTest( kind: "retained-evidence", evidence_id: summary.parent_evidence_id, }; - const readAll = async (view: Record) => { + const readAll = async (view: { + collection: "edges" | "nodes"; + document?: string; + }) => { const rows: unknown[] = []; let offset: number | null = 0; while (offset !== null) { @@ -142,7 +145,15 @@ mcpTest( paged.structuredContent, ).normalized_result; rows.push(...page.items); - offset = page.coverage.next_offset; + expect(rows.length).toBeLessThanOrEqual( + summary.summary.available_counts[view.collection], + ); + const nextOffset: number | null = page.coverage.next_offset; + if (nextOffset !== null) { + expect(page.items).toHaveLength(2); + expect(nextOffset).toBe(offset + 2); + } + offset = nextOffset; } return rows; };