Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(artifacts): preserve ZIP member identity and filename semantics
morluto7777abf473d4
diff --git a/src/artifacts/ArtifactPaths.test.ts b/src/artifacts/ArtifactPaths.test.tsindex 2300c63bb..5957bb825 100644--- a/src/artifacts/ArtifactPaths.test.ts+++ b/src/artifacts/ArtifactPaths.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import {+ ArtifactPathRegistry,annotateEnglishUnicodeCaseCollisions,ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION,} from "./ArtifactPaths.js";@@ -26,6 +27,15 @@ const annotate = (paths: readonly string[]) => {};describe("English Unicode case collisions", () => {+ it("retains repeated same-kind entries while rejecting file-directory aliasing", () => {+ const registry = new ArtifactPathRegistry();+ registry.add("duplicate", "file");+ expect(() => registry.add("duplicate", "file")).not.toThrow();+ expect(() => registry.add("duplicate", "directory")).toThrow(+ "Artifact path collision",+ );+ });+it("names the other spelling of a colliding file", () => {const { limitation, byPath } = annotate([".", "Main.js", "main.js", "x"]);expect(limitation).toBe(ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION);diff --git a/src/artifacts/ArtifactPaths.ts b/src/artifacts/ArtifactPaths.tsindex b83165907..2bc22f764 100644--- a/src/artifacts/ArtifactPaths.ts+++ b/src/artifacts/ArtifactPaths.ts@@ -61,7 +61,7 @@ export class ArtifactPathRegistry {}node = child;if (index === parts.length - 1) {- if (node.kind !== undefined)+ if (node.kind !== undefined && node.kind !== kind)throw new ArtifactReaderFailure("path",`Artifact path collision: ${path}`,diff --git a/src/artifacts/ZipArtifactReader.ts b/src/artifacts/ZipArtifactReader.tsindex 066b005b8..a53e01838 100644--- a/src/artifacts/ZipArtifactReader.ts+++ b/src/artifacts/ZipArtifactReader.ts@@ -171,6 +171,9 @@ export class ZipArtifactReader implements ArtifactReader {this.#reader = new ZipReader(this.#source, {checkSignature: true,checkOverlappingEntry: true,+ // Unflagged names use the ZIP legacy encoding (CP437); the UTF-8 flag+ // and validated Unicode Path extra fields remain authoritative.+ filenameEncoding: "cp437",// REA applies its own provider-neutral path validation in scanReader and// must preserve that typed failure instead of zip.js rejecting first.filenameValidation: "tolerant",diff --git a/src/artifacts/inventory/ArtifactGraphConstruction.test.ts b/src/artifacts/inventory/ArtifactGraphConstruction.test.tsindex 6531d4557..2b9b0bd81 100644--- a/src/artifacts/inventory/ArtifactGraphConstruction.test.ts+++ b/src/artifacts/inventory/ArtifactGraphConstruction.test.ts@@ -1,7 +1,127 @@import { describe, expect, it } from "vitest";import { CPU, fatImage, machoImage } from "../apple/MachoImage.fixture.js";-import { classifyArtifactContent } from "./ArtifactGraphConstruction.js";+import {+ classifyArtifactContent,+ createArtifactEdges,+ createOccurrence,+ indexOccurrencesByPath,+ resolveOccurrenceParents,+} from "./ArtifactGraphConstruction.js";+import { artifactIdForContent } from "../../domain/artifactIdentity.js";+import type { ArtifactEntry } from "../ArtifactReader.js";++const entry = (path: string, kind: ArtifactEntry["kind"]): ArtifactEntry => ({+ path,+ kind,+ declaredSize: null,+ compressedSize: null,+ executable: false,+ encrypted: false,+ byteOffset: null,+ declaredSha256: null,+ unpacked: false,+ limitations: [],+ adapterKey: path,+});++describe("occurrence parent ownership", () => {+ it("selects the nearest unique nested parent", () => {+ const outer = createOccurrence(entry("a", "directory"), "a", null);+ const inner = createOccurrence(entry("a/b", "directory"), "a/b", null);+ const file = createOccurrence(entry("a/b/file", "file"), "a/b/file", null);+ const occurrences = [outer, inner, file];++ resolveOccurrenceParents(+ occurrences,+ indexOccurrencesByPath(occurrences),+ new Set(),+ );++ expect(file.parent_occurrence_id).toBe(inner.occurrence_id);+ });++ it("leaves a child unparented when duplicate directories make ownership ambiguous", () => {+ const first = createOccurrence(entry("a", "directory"), "a", null, 0);+ const second = createOccurrence(entry("a", "directory"), "a", null, 1);+ const file = createOccurrence(entry("a/file", "file"), "a/file", null);+ const occurrences = [first, second, file];++ const resolution = resolveOccurrenceParents(+ occurrences,+ indexOccurrencesByPath(occurrences),+ new Set(),+ );++ expect(file.parent_occurrence_id).toBeNull();+ expect(resolution.unknownParentOccurrences.has(file)).toBe(true);+ expect(resolution.limitations).toContain(+ 'The parent occurrence for "a/file" is unknown because multiple observed directory or container occurrences share "a".',+ );+ expect([first, second].map(({ hash_status }) => hash_status)).toEqual([+ "unavailable",+ "unavailable",+ ]);+ });+});++describe("source-map artifact relationships", () => {+ const contentId = (digit: string): string =>+ artifactIdForContent(digit.repeat(64));++ it.each([+ ["missing target", [] as string[], "contains"],+ ["unread target", ["unread"] as string[], "contains"],+ ["unique identified target", ["identified"] as string[], "maps-source"],+ ["duplicate targets", ["identified", "identified"] as string[], "contains"],+ ] as const)(+ "uses a truthful edge for a %s",+ (_label, targetIdentities, relation) => {+ const directory = createOccurrence(+ entry("app", "directory"),+ "app",+ null,+ );+ directory.artifact_id = contentId("1");+ const targets = targetIdentities.map((identity, index) => {+ const target = createOccurrence(+ entry("app/main.js", "file"),+ "app/main.js",+ directory.occurrence_id,+ index,+ );+ target.artifact_id = identity === "unread" ? null : contentId("2");+ return target;+ });+ const sourceMap = createOccurrence(+ entry("app/main.js.map", "file"),+ "app/main.js.map",+ directory.occurrence_id,+ );+ sourceMap.artifact_id = contentId("3");++ const result = createArtifactEdges(contentId("4"), [+ directory,+ ...targets,+ sourceMap,+ ]);+ const edge = result.edges.find(+ ({ occurrence_id }) => occurrence_id === sourceMap.occurrence_id,+ );++ expect(edge).toMatchObject({+ relation,+ parent_artifact_id:+ relation === "maps-source" ? contentId("2") : contentId("1"),+ occurrence_id: sourceMap.occurrence_id,+ });+ expect(result.limitations.length > 0).toBe(+ (targetIdentities.length === 1 && targetIdentities[0] === "unread") ||+ targetIdentities.length > 1,+ );+ },+ );+});const fat = (wide = false): Buffer =>Buffer.from(fatImage([{ cpu: CPU.arm64, bytes: machoImage({}) }], wide));diff --git a/src/artifacts/inventory/ArtifactGraphConstruction.ts b/src/artifacts/inventory/ArtifactGraphConstruction.tsindex f2564d254..654a40244 100644--- a/src/artifacts/inventory/ArtifactGraphConstruction.ts+++ b/src/artifacts/inventory/ArtifactGraphConstruction.ts@@ -50,14 +50,17 @@ export interface MutableOccurrence {limitations: string[];}-/** Index the first occurrence for each canonical logical path. */+/** Index every occurrence by canonical logical path without choosing an owner. */export const indexOccurrencesByPath = (occurrences: readonly MutableOccurrence[],-): ReadonlyMap<string, MutableOccurrence> => {- const byPath = new Map<string, MutableOccurrence>();- for (const occurrence of occurrences)- if (!byPath.has(occurrence.logical_path))- byPath.set(occurrence.logical_path, occurrence);+): ReadonlyMap<string, readonly MutableOccurrence[]> => {+ const byPath = new Map<string, MutableOccurrence[]>();+ for (const occurrence of occurrences) {+ const matches = byPath.get(occurrence.logical_path);+ if (matches === undefined)+ byPath.set(occurrence.logical_path, [occurrence]);+ else matches.push(occurrence);+ }return byPath;};@@ -70,6 +73,7 @@ export const createOccurrence = (entry: ArtifactEntry,path: string,parent: string | null,+ duplicateOrdinal = 0,): MutableOccurrence => {const role =entry.kind === "directory"@@ -83,7 +87,12 @@ export const createOccurrence = (? classifyArtifactPath(path): ({ kind: "unknown", format: "unknown" } as const);return {- occurrence_id: `occ_${digestCanonicalValue({ path, kind: entry.kind }, "Artifact")}`,+ occurrence_id: `occ_${digestCanonicalValue(+ duplicateOrdinal === 0+ ? { path, kind: entry.kind }+ : { path, kind: entry.kind, duplicate_ordinal: duplicateOrdinal },+ "Artifact",+ )}`,artifact_id: null,parent_occurrence_id: parent,logical_path: path,@@ -128,7 +137,10 @@ export const materializeDirectoryNodes = (nodes: Map<string, ArtifactNode>,): void => {const directories = occurrences- .filter(({ entry_kind: kind }) => kind === "directory")+ .filter(+ ({ entry_kind: kind, hash_status }) =>+ kind === "directory" && hash_status !== "unavailable",+ ).sort((left, right) => depth(right.logical_path) - depth(left.logical_path),);@@ -249,15 +261,20 @@ export const rekeyOccurrences = (occurrences: MutableOccurrence[],): void => {const replacements = new Map<string, string>();- for (const occurrence of occurrences)+ const ordinalByPath = new Map<string, number>();+ for (const occurrence of occurrences) {+ const ordinal = ordinalByPath.get(occurrence.logical_path) ?? 0;+ ordinalByPath.set(occurrence.logical_path, ordinal + 1);replacements.set(occurrence.occurrence_id,occurrenceIdForLocation({rootArtifactId,logicalPath: occurrence.logical_path,entryKind: occurrence.entry_kind,+ ...(ordinal === 0 ? {} : { duplicateOrdinal: ordinal }),}),);+ }for (const occurrence of occurrences) {occurrence.occurrence_id =replacements.get(occurrence.occurrence_id) ?? occurrence.occurrence_id;@@ -272,19 +289,45 @@ export const createArtifactEdges = (rootArtifactId: string,occurrences: MutableOccurrence[],producer?: ArtifactCommand,-): ArtifactEdge[] => {+): { readonly edges: ArtifactEdge[]; readonly limitations: string[] } => {const byId = new Map(occurrences.map((item) => [item.occurrence_id, item]));const byPath = indexOccurrencesByPath(occurrences);const edges: ArtifactEdge[] = [];+ const limitations: string[] = [];for (const occurrence of occurrences) {+ const isSourceMap = occurrence.logical_path.toLowerCase().endsWith(".map");+ const sourcePath = isSourceMap+ ? occurrence.logical_path.slice(0, -".map".length)+ : undefined;+ const sourceCandidates =+ sourcePath === undefined ? [] : (byPath.get(sourcePath) ?? []);+ const mappedSource =+ sourceCandidates.length === 1 && sourceCandidates[0]?.artifact_id !== null+ ? sourceCandidates[0]+ : undefined;+ if (sourcePath !== undefined) {+ const unknownMapping =+ sourceCandidates.length > 1+ ? {+ occurrence: `Source-map target is unknown because multiple occurrences share ${JSON.stringify(sourcePath)}.`,+ coverage: `Source-map relationships are unknown because multiple occurrences share ${JSON.stringify(sourcePath)}.`,+ }+ : sourceCandidates.length === 1 && mappedSource === undefined+ ? {+ occurrence: `Source-map target identity is unknown because the matching occurrence at ${JSON.stringify(sourcePath)} has no content identity.`,+ coverage: `Source-map relationships are unknown because the matching occurrence at ${JSON.stringify(sourcePath)} has no content identity.`,+ }+ : undefined;+ if (unknownMapping !== undefined) {+ occurrence.limitations.push(unknownMapping.occurrence);+ limitations.push(unknownMapping.coverage);+ }+ }if (occurrence.parent_occurrence_id === null ||occurrence.artifact_id === null)continue;- const mappedSource = occurrence.logical_path.toLowerCase().endsWith(".map")- ? byPath.get(occurrence.logical_path.slice(0, -".map".length))- : undefined;const parentArtifactId =mappedSource?.artifact_id ??byId.get(occurrence.parent_occurrence_id)?.artifact_id ??@@ -294,7 +337,9 @@ export const createArtifactEdges = (relation:occurrence.entry_kind === "slice"? ("slice-of" as const)- : relationFor(occurrence.logical_path),+ : isSourceMap && mappedSource === undefined+ ? ("contains" as const)+ : relationFor(occurrence.logical_path),occurrence_id: occurrence.occurrence_id,};edges.push({@@ -304,29 +349,44 @@ export const createArtifactEdges = (ordinal: edges.length,});}- return edges;+ return { edges, limitations };};interface ArtifactParentIndex {readonly children: Map<string, ArtifactParentIndex>;- occurrence?: MutableOccurrence;+ occurrences?: readonly MutableOccurrence[];}/** Resolve strict observed ancestors without rebuilding every path prefix. */export const resolveOccurrenceParents = (occurrences: readonly MutableOccurrence[],- byPath: ReadonlyMap<string, MutableOccurrence>,+ byPath: ReadonlyMap<string, readonly MutableOccurrence[]>,expandedContainerIds: ReadonlySet<string>,-): void => {+): {+ readonly limitations: readonly string[];+ readonly unknownParentOccurrences: ReadonlySet<MutableOccurrence>;+} => {const root: ArtifactParentIndex = { children: new Map() };- for (const occurrence of byPath.values()) {- if (- occurrence.entry_kind !== "directory" &&- !expandedContainerIds.has(occurrence.occurrence_id)- )- continue;+ for (const matches of byPath.values()) {+ const parents = matches.filter(+ (occurrence) =>+ occurrence.entry_kind === "directory" ||+ expandedContainerIds.has(occurrence.occurrence_id),+ );+ if (parents.length === 0) continue;+ if (parents.length > 1)+ for (const parent of parents)+ if (parent.entry_kind === "directory") {+ parent.artifact_id = null;+ parent.hash_status = "unavailable";+ parent.limitations.push(+ "This directory occurrence cannot be materialized because multiple directory entries share its logical path.",+ );+ }+ const path = matches[0]?.logical_path;+ if (path === undefined) continue;let branch = root;- for (const segment of occurrence.logical_path.split("/")) {+ for (const segment of path.split("/")) {let child = branch.children.get(segment);if (child === undefined) {child = { children: new Map() };@@ -334,12 +394,16 @@ export const resolveOccurrenceParents = (}branch = child;}- branch.occurrence = occurrence;+ branch.occurrences = parents;}+ const limitations = new Set<string>();+ const unknownParentOccurrences = new Set<MutableOccurrence>();for (const occurrence of occurrences) {const path = occurrence.logical_path;let branch = root;let parent: MutableOccurrence | undefined;+ let ambiguousParentPath: string | undefined;+ let prefix = "";// Walk parent segments only. Stop scanning the path once no observed// directory or expanded container can be an ancestor.for (let start = 0; ;) {@@ -349,11 +413,29 @@ export const resolveOccurrenceParents = (const child = branch.children.get(segment);if (child === undefined) break;branch = child;- parent = branch.occurrence ?? parent;+ prefix = prefix.length === 0 ? segment : `${prefix}/${segment}`;+ const candidates = branch.occurrences ?? [];+ if (candidates.length === 1) {+ parent = candidates[0];+ ambiguousParentPath = undefined;+ } else if (candidates.length > 1) {+ parent = undefined;+ ambiguousParentPath = prefix;+ }start = slash + 1;}occurrence.parent_occurrence_id = parent?.occurrence_id ?? null;+ if (ambiguousParentPath !== undefined) {+ const limitation = `The parent occurrence for ${JSON.stringify(path)} is unknown because multiple observed directory or container occurrences share ${JSON.stringify(ambiguousParentPath)}.`;+ occurrence.limitations.push(limitation);+ limitations.add(limitation);+ unknownParentOccurrences.add(occurrence);+ }}+ return {+ limitations: [...limitations].sort(compareUnicodeCodePoints),+ unknownParentOccurrences,+ };};/**diff --git a/src/artifacts/inventory/scanCanonical.ts b/src/artifacts/inventory/scanCanonical.tsindex 2c8679e21..a6cdceeb2 100644--- a/src/artifacts/inventory/scanCanonical.ts+++ b/src/artifacts/inventory/scanCanonical.ts@@ -23,7 +23,6 @@ import {import {createArtifactEdges,createRootNode,- indexOccurrencesByPath,materializeDirectoryNodes,rekeyOccurrences,rootOccurrenceFor,@@ -100,6 +99,7 @@ export const scanCanonicalArtifactInventoryInScope = async (occurrences,pendingContradictions,caseCollisionLimitation,+ unknownParentOccurrences,traversal,} = await scanReader(reader, ownedReaders, options.signal, integrity);outcome = {@@ -117,6 +117,7 @@ export const scanCanonicalArtifactInventoryInScope = async (occurrences,pendingContradictions,caseCollisionLimitation,+ unknownParentOccurrences,traversal,}),};@@ -199,6 +200,7 @@ interface SnapshotBuildInput {readonly occurrences: MutableOccurrence[];readonly pendingContradictions: PendingIntegrityContradiction[];readonly caseCollisionLimitation: string | undefined;+ readonly unknownParentOccurrences: ReadonlySet<MutableOccurrence>;readonly traversal: ArtifactReaderTraversal;}@@ -221,7 +223,10 @@ const buildInventorySnapshot = async (path,});for (const occurrence of input.occurrences)- if (occurrence.parent_occurrence_id === null)+ if (+ occurrence.parent_occurrence_id === null &&+ !input.unknownParentOccurrences.has(occurrence)+ )occurrence.parent_occurrence_id = rootOccurrence.occurrence_id;input.occurrences.unshift(rootOccurrence);@@ -231,18 +236,17 @@ const buildInventorySnapshot = async (occurrence,]),);- const occurrenceByPath = indexOccurrencesByPath(input.occurrences);const integrityContradictions = buildIntegrityContradictions(input.pendingContradictions,- occurrenceByPath,occurrenceById,rootNode,);- const edges = createArtifactEdges(+ const edgeResult = createArtifactEdges(rootNode.artifact_id,input.occurrences,reader?.provenance()[0],);+ const { edges } = edgeResult;const orderedNodes = sortNodes([...input.nodes.values()]);const orderedOccurrences = sortOccurrences(input.occurrences);const orderedEdges = sortEdges(edges).map((edge, ordinal) => ({@@ -273,6 +277,10 @@ const buildInventorySnapshot = async (orderedEdges,});const traversal = inventoryCoverage(rootFormat, reader, input.traversal);+ const coverage =+ edgeResult.limitations.length === 0+ ? traversal.coverage+ : { ...traversal.coverage, status: "unknown" as const };return {manifest,nodes: orderedNodes,@@ -280,11 +288,10 @@ const buildInventorySnapshot = async (edges: orderedEdges,provenance: reader?.provenance() ?? [],integrity_contradictions: integrityContradictions,- coverage: traversal.coverage,- coverage_status:- traversal.coverage.status === "complete" ? "complete" : "partial",+ coverage,+ coverage_status: coverage.status === "complete" ? "complete" : "partial",limitations: buildLimitations(- traversal.limitations,+ [...traversal.limitations, ...edgeResult.limitations],integrityContradictions,input.caseCollisionLimitation,),@@ -293,17 +300,11 @@ const buildInventorySnapshot = async (const buildIntegrityContradictions = (pending: readonly PendingIntegrityContradiction[],- occurrenceByPath: ReadonlyMap<string, MutableOccurrence>,occurrenceById: ReadonlyMap<string, MutableOccurrence>,rootNode: ArtifactNode,): IntegrityContradiction[] =>pending.map((contradiction): IntegrityContradiction => {- const occurrence = occurrenceByPath.get(contradiction.logicalPath);- if (occurrence === undefined)- throw new ArtifactReaderFailure(- "integrity",- "Integrity contradiction lost its graph occurrence",- );+ const occurrence = contradiction.occurrence;const parent =occurrence.parent_occurrence_id === null? undefined@@ -312,13 +313,13 @@ const buildIntegrityContradictions = (return {contradiction_id: artifactContradictionId({rootArtifactId: rootNode.artifact_id,- logicalPath: contradiction.logicalPath,+ logicalPath: occurrence.logical_path,declaredSha256: contradiction.declaredSha256,observedSha256: contradiction.observedSha256,}),occurrence_id: occurrence.occurrence_id,parent_artifact_id: parentArtifactId,- logical_path: contradiction.logicalPath,+ logical_path: occurrence.logical_path,declared_sha256: contradiction.declaredSha256,observed_sha256: contradiction.observedSha256,entry_kind: contradiction.entryKind,diff --git a/src/artifacts/inventory/scanReader.ts b/src/artifacts/inventory/scanReader.tsindex 38b67d843..88ad14c80 100644--- a/src/artifacts/inventory/scanReader.ts+++ b/src/artifacts/inventory/scanReader.ts@@ -21,6 +21,7 @@ import {createArtifactNode,createOccurrence,noteUnreadContainerSuffix,+ indexOccurrencesByPath,resolveOccurrenceParents,type MutableOccurrence,} from "./ArtifactGraphConstruction.js";@@ -31,7 +32,7 @@ import {import { hashReadable } from "../ArtifactHash.js";export interface PendingIntegrityContradiction {- readonly logicalPath: string;+ readonly occurrence: MutableOccurrence;readonly declaredSha256: string;readonly observedSha256: string;readonly entryKind: "file" | "slice";@@ -54,7 +55,7 @@ interface ScanContext {readonly nodes: Map<string, ArtifactNode>;readonly occurrences: MutableOccurrence[];readonly pendingContradictions: PendingIntegrityContradiction[];- readonly occurrenceByPath: Map<string, MutableOccurrence>;+ readonly occurrenceCountByPath: Map<string, number>;readonly registry: ArtifactPathRegistry;readonly expandedContainerIds: Set<string>;readonly ownedReaders: ArtifactReader[];@@ -71,6 +72,7 @@ export const scanReader = async (readonly occurrences: MutableOccurrence[];readonly pendingContradictions: PendingIntegrityContradiction[];readonly caseCollisionLimitation: string | undefined;+ readonly unknownParentOccurrences: ReadonlySet<MutableOccurrence>;readonly traversal: ArtifactReaderTraversal;}> => {const { nodes, occurrences, pendingContradictions } = emptyScan();@@ -80,6 +82,7 @@ export const scanReader = async (occurrences,pendingContradictions,caseCollisionLimitation: undefined,+ unknownParentOccurrences: new Set(),traversal: { status: "complete", limitations: [] },};const context: ScanContext = {@@ -89,7 +92,7 @@ export const scanReader = async (nodes,occurrences,pendingContradictions,- occurrenceByPath: new Map<string, MutableOccurrence>(),+ occurrenceCountByPath: new Map<string, number>(),registry: new ArtifactPathRegistry(),expandedContainerIds: new Set<string>(),ownedReaders,@@ -98,25 +101,32 @@ export const scanReader = async (await visitArtifactEntries(context, reader, "");// Archive directories may appear after their children. Resolve containment// against the complete index before directory identities are materialized.- resolveOccurrenceParents(+ const byPath = indexOccurrencesByPath(occurrences);+ const parentResolution = resolveOccurrenceParents(occurrences,- context.occurrenceByPath,+ byPath,context.expandedContainerIds,);+ const structuralLimitations = [...parentResolution.limitations];return {nodes,occurrences,pendingContradictions,caseCollisionLimitation: annotateEnglishUnicodeCaseCollisions(occurrences),+ unknownParentOccurrences: parentResolution.unknownParentOccurrences,traversal: {- status: context.omissions.length === 0 ? "complete" : "unknown",+ status:+ context.omissions.length === 0 && structuralLimitations.length === 0+ ? "complete"+ : "unknown",limitations: [- ...new Set(- context.omissions.map(+ ...new Set([+ ...context.omissions.map(({ path, kind }) =>`Artifact traversal omitted ${kind} at ${JSON.stringify(path)}.`,),- ),+ ...structuralLimitations,+ ]),].sort(compareUnicodeCodePoints),},};@@ -176,7 +186,15 @@ const visitArtifactEntries = async (logicalPath,expandableAsar ? "directory" : entry.kind,);- const occurrence = createOccurrence(entry, logicalPath, null);+ const duplicateOrdinal =+ context.occurrenceCountByPath.get(logicalPath) ?? 0;+ context.occurrenceCountByPath.set(logicalPath, duplicateOrdinal + 1);+ const occurrence = createOccurrence(+ entry,+ logicalPath,+ null,+ duplicateOrdinal,+ );let digested:| {readonly node: ArtifactNode;@@ -190,6 +208,7 @@ const visitArtifactEntries = async (frame.reader,entry,logicalPath,+ occurrence,);} catch (cause: unknown) {if (!isUnavailableUnpackedEntry(cause, entry)) throw cause;@@ -211,7 +230,6 @@ const visitArtifactEntries = async ();}context.occurrences.push(occurrence);- context.occurrenceByPath.set(logicalPath, occurrence);if (expandableAsar &&digested !== undefined &&@@ -258,6 +276,7 @@ const digestArtifactEntry = async (currentReader: ArtifactReader,entry: ArtifactEntry,logicalPath: string,+ occurrence: MutableOccurrence,): Promise<| {readonly node: ArtifactNode;@@ -288,7 +307,7 @@ const digestArtifactEntry = async (},);context.pendingContradictions.push({- logicalPath,+ occurrence,declaredSha256: entry.declaredSha256,observedSha256: digest.sha256,entryKind: entry.kind,diff --git a/src/domain/artifactComparison.ts b/src/domain/artifactComparison.tsindex 72494136c..76d59f4e3 100644--- a/src/domain/artifactComparison.ts+++ b/src/domain/artifactComparison.ts@@ -131,6 +131,20 @@ export const compareArtifacts = ((rootCoverageComplete &&left.inventory.manifest.occurrence_count === 1 &&right.inventory.manifest.occurrence_count === 1));+ const leftOccurrencesByPath = occurrencesByPath(left.inventory.occurrences);+ const rightOccurrencesByPath = occurrencesByPath(right.inventory.occurrences);+ const comparison = compareOccurrences(+ left.inventory,+ right.inventory,+ leftOccurrencesByPath,+ rightOccurrencesByPath,+ [+ ...left.evidence.map(({ evidence_id: id }) => id),+ ...right.evidence.map(({ evidence_id: id }) => id),+ ],+ { root: rootCoverageComplete, entries: entryCoverageComplete },+ );+ const changes = comparison.changes;const limitations = [...left.inventory.limitations.map((item) => `Left: ${item}`),...right.inventory.limitations.map((item) => `Right: ${item}`),@@ -149,16 +163,12 @@ export const compareArtifacts = (...(right.inventory.coverage.status === "complete"? []: ["Right artifact inventory traversal coverage is unknown."]),+ ...(comparison.hasAmbiguousDuplicatePaths+ ? [+ "Duplicate logical paths cannot be paired across inventories; comparisons for those paths are unknown.",+ ]+ : []),];- const changes = compareOccurrences(- left.inventory,- right.inventory,- [- ...left.evidence.map(({ evidence_id: id }) => id),- ...right.evidence.map(({ evidence_id: id }) => id),- ],- { root: rootCoverageComplete, entries: entryCoverageComplete },- );applyRootHashChange(left.inventory, right.inventory, changes, [...left.evidence.map(({ evidence_id: id }) => id),...right.evidence.map(({ evidence_id: id }) => id),@@ -195,15 +205,14 @@ export const compareArtifacts = (const compareOccurrences = (left: InventorySet,right: InventorySet,+ leftByPath: ReadonlyMap<string, ArtifactOccurrence[]>,+ rightByPath: ReadonlyMap<string, ArtifactOccurrence[]>,evidenceLinks: readonly string[],coverage: { readonly root: boolean; readonly entries: boolean },-): ArtifactChange[] => {- const leftByPath = new Map(- left.occurrences.map((item) => [item.logical_path, item]),- );- const rightByPath = new Map(- right.occurrences.map((item) => [item.logical_path, item]),- );+): {+ readonly changes: ArtifactChange[];+ readonly hasAmbiguousDuplicatePaths: boolean;+} => {const leftNodes = new Map(left.nodes.map((item) => [item.artifact_id, item]));const rightNodes = new Map(right.nodes.map((item) => [item.artifact_id, item]),@@ -214,9 +223,26 @@ const compareOccurrences = (...new Set([...leftByPath.keys(), ...rightByPath.keys()]),].sort(compareUnicodeCodePoints);const output: ArtifactChange[] = [];+ let hasAmbiguousDuplicatePaths = false;for (const path of paths) {- const leftOccurrence = leftByPath.get(path);- const rightOccurrence = rightByPath.get(path);+ const leftMatches = leftByPath.get(path) ?? [];+ const rightMatches = rightByPath.get(path) ?? [];+ if (leftMatches.length > 1 || rightMatches.length > 1) {+ hasAmbiguousDuplicatePaths = true;+ output.push({+ logical_path: path,+ classification: "unknown",+ dimensions: ["availability"],+ left_occurrence_id: null,+ right_occurrence_id: null,+ left_artifact_id: null,+ right_artifact_id: null,+ evidence_links: [...evidenceLinks],+ });+ continue;+ }+ const leftOccurrence = leftMatches[0];+ const rightOccurrence = rightMatches[0];const change = classifyPath({path,leftOccurrence,@@ -231,6 +257,19 @@ const compareOccurrences = (});if (change !== null) output.push(change);}+ return { changes: output, hasAmbiguousDuplicatePaths };+};++const occurrencesByPath = (+ occurrences: readonly ArtifactOccurrence[],+): ReadonlyMap<string, ArtifactOccurrence[]> => {+ const output = new Map<string, ArtifactOccurrence[]>();+ for (const occurrence of occurrences) {+ const matches = output.get(occurrence.logical_path);+ if (matches === undefined)+ output.set(occurrence.logical_path, [occurrence]);+ else matches.push(occurrence);+ }return output;};diff --git a/src/domain/artifactIdentity.ts b/src/domain/artifactIdentity.tsindex 8321129a9..45e928712 100644--- a/src/domain/artifactIdentity.ts+++ b/src/domain/artifactIdentity.ts@@ -38,6 +38,7 @@ export const occurrenceIdForLocation = (input: {readonly rootArtifactId: string;readonly logicalPath: string;readonly entryKind: ArtifactOccurrence["entry_kind"];+ readonly duplicateOrdinal?: number;}): string =>input.logicalPath === "."? `occ_${digestCanonicalValue({ root: input.rootArtifactId }, "Artifact")}`@@ -46,6 +47,9 @@ export const occurrenceIdForLocation = (input: {root_artifact_id: input.rootArtifactId,logical_path: input.logicalPath,entry_kind: input.entryKind,+ ...(input.duplicateOrdinal === undefined+ ? {}+ : { duplicate_ordinal: input.duplicateOrdinal }),},"Artifact",)}`;diff --git a/src/domain/artifactInventoryEvidence.ts b/src/domain/artifactInventoryEvidence.tsindex 5c0112d4c..afaabac49 100644--- a/src/domain/artifactInventoryEvidence.ts+++ b/src/domain/artifactInventoryEvidence.ts@@ -120,10 +120,6 @@ const validateInventoryPage = (inventory: ArtifactInventoryResult): void => {inventory.occurrences.map(({ occurrence_id: id }) => id),"occurrence ID",);- assertUnique(- inventory.occurrences.map(({ logical_path: path }) => path),- "logical path",- );assertUnique(inventory.edges.map(({ edge_id: id }) => id),"edge ID",@@ -149,7 +145,6 @@ const assembleInventoryResults = ();const nodes = new Map<string, ArtifactNode>();const occurrences = new Map<string, ArtifactOccurrence>();- const paths = new Map<string, ArtifactOccurrence>();const edges = new Map<string, ArtifactInventoryResult["edges"][number]>();for (const page of pages) {if (canonicalJson(page.manifest, "Artifact inventory") !== manifestJson)@@ -182,7 +177,6 @@ const assembleInventoryResults = (occurrence,"occurrence",);- mergeExact(paths, occurrence.logical_path, occurrence, "logical path");}for (const edge of page.edges)mergeExact(edges, edge.edge_id, edge, "edge");@@ -211,9 +205,9 @@ const orderedInventory = (const nodes = [...values.nodes.values()].sort((left, right) =>compareUnicodeCodePoints(left.artifact_id, right.artifact_id),);- const occurrences = [...values.occurrences.values()].sort((left, right) =>- compareUnicodeCodePoints(left.logical_path, right.logical_path),- );+ const occurrences = orderOccurrences(first.manifest.root_artifact_id, [+ ...values.occurrences.values(),+ ]);const edges = [...values.edges.values()].sort((left, right) =>compareUnicodeCodePoints(left.edge_id, right.edge_id),);@@ -235,6 +229,44 @@ const orderedInventory = (};};+const orderOccurrences = (+ rootArtifactId: string,+ occurrences: readonly ArtifactOccurrence[],+): ArtifactOccurrence[] => {+ const groups = new Map<string, ArtifactOccurrence[]>();+ for (const occurrence of occurrences) {+ const group = groups.get(occurrence.logical_path);+ if (group === undefined) groups.set(occurrence.logical_path, [occurrence]);+ else group.push(occurrence);+ }+ return [...groups]+ .sort(([left], [right]) => compareUnicodeCodePoints(left, right))+ .flatMap(([path, group]) => {+ if (group.length < 2) return group;+ const ordinalById = new Map<string, number>();+ const first = group[0];+ if (first === undefined)+ throw new TypeError("Duplicate occurrence group is empty");+ for (let ordinal = 0; ordinal < group.length; ordinal++) {+ ordinalById.set(+ occurrenceIdForLocation({+ rootArtifactId,+ logicalPath: path,+ entryKind: first.entry_kind,+ ...(ordinal === 0 ? {} : { duplicateOrdinal: ordinal }),+ }),+ ordinal,+ );+ }+ return group.sort(+ (left, right) =>+ (ordinalById.get(left.occurrence_id) ?? Number.MAX_SAFE_INTEGER) -+ (ordinalById.get(right.occurrence_id) ?? Number.MAX_SAFE_INTEGER) ||+ compareUnicodeCodePoints(left.occurrence_id, right.occurrence_id),+ );+ });+};+// Normalize both retained coverage formats at this owning boundary.const resolveInventoryCoverage = (inventory: ArtifactInventoryResult,@@ -312,8 +344,12 @@ const validateCompleteInventory = (inventory: InventorySet): void => {throw new TypeError("Artifact root occurrence does not match its manifest representation",);- for (const occurrence of inventory.occurrences)- validateOccurrence(occurrence, inventory, nodeIds, occurrenceIds);+ const duplicateOrdinalByPath = new Map<string, number>();+ for (const occurrence of inventory.occurrences) {+ const ordinal = duplicateOrdinalByPath.get(occurrence.logical_path) ?? 0;+ duplicateOrdinalByPath.set(occurrence.logical_path, ordinal + 1);+ validateOccurrence(occurrence, inventory, nodeIds, occurrenceIds, ordinal);+ }const occurrencesById = new Map(inventory.occurrences.map((occurrence) => [occurrence.occurrence_id,@@ -362,6 +398,7 @@ const validateOccurrence = (inventory: InventorySet,nodeIds: ReadonlySet<string>,occurrenceIds: ReadonlySet<string>,+ duplicateOrdinal: number,): void => {if (occurrence.artifact_id !== null && !nodeIds.has(occurrence.artifact_id))throw new TypeError("Artifact occurrence references a missing node");@@ -374,6 +411,7 @@ const validateOccurrence = (rootArtifactId: inventory.manifest.root_artifact_id,logicalPath: occurrence.logical_path,entryKind: occurrence.entry_kind,+ ...(duplicateOrdinal === 0 ? {} : { duplicateOrdinal }),});if (occurrence.occurrence_id !== expectedId)throw new TypeError("Artifact occurrence ID does not match its identity");diff --git a/tests/boundary/filesystem/artifactComparison.test.ts b/tests/boundary/filesystem/artifactComparison.test.tsindex 3dc2edb66..36e6bf945 100644--- a/tests/boundary/filesystem/artifactComparison.test.ts+++ b/tests/boundary/filesystem/artifactComparison.test.ts@@ -445,6 +445,179 @@ describe("artifact comparison completeness", () => {}, 15_000);});+describe("artifact source-map relationship coverage", () => {+ it("preserves unknown source-map relationships for duplicate ZIP paths", async () => {+ const root = await createTestTempDirectory("rea-duplicate-source-map-");+ const path = join(root, "duplicate-source-map.zip");+ const writer = new ZipWriter(new Uint8ArrayWriter());+ await writer.add("main.js", new TextReader("first();"), { level: 0 });+ await writer.add("your.js", new TextReader("second();"), { level: 0 });+ await writer.add("main.js.map", new TextReader("{}"), { level: 0 });+ const bytes = Buffer.from(await writer.close());+ for (const [signature, headerSize] of [+ [Buffer.from([0x50, 0x4b, 0x03, 0x04]), 30],+ [Buffer.from([0x50, 0x4b, 0x01, 0x02]), 46],+ ] as const) {+ const first = bytes.indexOf(signature);+ const second = bytes.indexOf(signature, first + 4);+ if (first < 0 || second <= first)+ throw new Error("Expected both source ZIP member headers");+ expect(+ bytes.subarray(second + headerSize, second + headerSize + 7).toString(),+ ).toBe("your.js");+ bytes.write("main.js", second + headerSize);+ }+ await writeFile(path, bytes);++ const evidence = await observe(path);+ const parsed = parseArtifactInventoryEvidence(evidence);+ const { inventory } = parsed;+ const map = inventory.occurrences.find(+ ({ logical_path }) => logical_path === "main.js.map",+ );+ if (map === undefined) throw new Error("Expected source-map occurrence");+ const mapEdge = inventory.edges.find(+ ({ occurrence_id }) => occurrence_id === map.occurrence_id,+ );++ expect(inventory.coverage?.status).toBe("unknown");+ expect(map.limitations).toContain(+ 'Source-map target is unknown because multiple occurrences share "main.js".',+ );+ expect(mapEdge).toMatchObject({ relation: "contains" });+ expect(mapEdge?.relation).not.toBe("maps-source");+ expect(inventory.integrityContradictions).toEqual([]);+ expect(+ inventory.limitations.some((limitation) =>+ limitation.toLowerCase().includes("integrity"),+ ),+ ).toBe(false);+ });+});++describe("duplicate archive occurrence ownership", () => {+ it("keeps directory ancestry unknown when ZIP directory paths repeat", async () => {+ const root = await createTestTempDirectory(+ "rea-artifact-duplicate-directory-",+ );+ const path = join(root, "duplicate-directories.zip");+ const writer = new ZipWriter(new Uint8ArrayWriter());+ await writer.add("x/", new TextReader(""));+ await writer.add("y/", new TextReader(""));+ await writer.add("x/file.txt", new TextReader("member"));+ const bytes = Buffer.from(await writer.close());+ for (const [signature, headerSize] of [+ [Buffer.from([0x50, 0x4b, 0x03, 0x04]), 30],+ [Buffer.from([0x50, 0x4b, 0x01, 0x02]), 46],+ ] as const) {+ const first = bytes.indexOf(signature);+ const second = bytes.indexOf(signature, first + 4);+ if (first < 0 || second <= first)+ throw new Error("Expected both ZIP directory headers");+ expect(+ bytes.subarray(second + headerSize, second + headerSize + 2).toString(),+ ).toBe("y/");+ bytes.write("x/", second + headerSize);+ }+ await writeFile(path, bytes);++ const evidence = await observe(path);+ const inventory = parseArtifactInventoryEvidence(evidence).inventory;+ const directory = inventory.occurrences.filter(+ ({ logical_path }) => logical_path === "x",+ );+ const child = inventory.occurrences.find(+ ({ logical_path }) => logical_path === "x/file.txt",+ );+ expect(directory).toHaveLength(2);+ expect(directory.every(({ artifact_id }) => artifact_id === null)).toBe(+ true,+ );+ expect(child?.parent_occurrence_id).toBeNull();+ expect(child?.limitations).toContain(+ 'The parent occurrence for "x/file.txt" is unknown because multiple observed directory or container occurrences share "x".',+ );+ expect(inventory.coverage.status).toBe("unknown");+ });++ it("retains duplicate path occurrences across pages and leaves pairing unknown", async () => {+ const root = await createTestTempDirectory("rea-artifact-duplicate-pages-");+ const archives = [join(root, "left.zip"), join(root, "right.zip")] as const;+ for (const [index, path] of archives.entries()) {+ const writer = new ZipWriter(new Uint8ArrayWriter());+ await writer.add("x.txt", new TextReader("first"));+ await writer.add(+ "y.txt",+ new TextReader(index === 0 ? "second-left" : "second-right"),+ );+ await writer.add("neighbor.txt", new TextReader("neighbor"));+ const bytes = Buffer.from(await writer.close());+ // Produce a duplicate path the same way as real malformed/ambiguous ZIP+ // inputs: retain each member record and rewrite only the equal-length name.+ for (const [signature, headerSize] of [+ [Buffer.from([0x50, 0x4b, 0x03, 0x04]), 30],+ [Buffer.from([0x50, 0x4b, 0x01, 0x02]), 46],+ ] as const) {+ const first = bytes.indexOf(signature);+ const second = bytes.indexOf(signature, first + 4);+ if (first < 0 || second <= first)+ throw new Error("Expected both ZIP member headers");+ expect(+ bytes+ .subarray(second + headerSize, second + headerSize + 5)+ .toString(),+ ).toBe("y.txt");+ bytes.write("x.txt", second + headerSize);+ }+ await writeFile(path, bytes);+ }++ const [left, right] = await Promise.all([+ observe(archives[0]),+ observe(archives[1]),+ ]);+ const parsed = parseArtifactInventoryEvidence(left);+ const repeated = parsed.inventory.occurrences.filter(+ ({ logical_path }) => logical_path === "x.txt",+ );+ expect(repeated).toHaveLength(2);+ expect(+ new Set(repeated.map(({ occurrence_id }) => occurrence_id)).size,+ ).toBe(2);++ const leftPages = fragmentInventoryEvidence(left, 2);+ const parsedPages = parseArtifactInventoryEvidence(leftPages);+ expect(+ parsedPages.inventory.occurrences.filter(+ ({ logical_path }) => logical_path === "x.txt",+ ),+ ).toHaveLength(2);++ const comparison = compareArtifacts(+ leftPages,+ fragmentInventoryEvidence(right, 2),+ );+ expect(comparison).toMatchObject({+ status: "unknown",+ summary: { unknown: expect.any(Number) },+ changes: expect.arrayContaining([+ expect.objectContaining({+ logical_path: "x.txt",+ classification: "unknown",+ dimensions: ["availability"],+ left_occurrence_id: null,+ right_occurrence_id: null,+ left_artifact_id: null,+ right_artifact_id: null,+ }),+ ]),+ });+ expect(comparison.limitations).toContain(+ "Duplicate logical paths cannot be paired across inventories; comparisons for those paths are unknown.",+ );+ });+});+describe("artifact comparison fragment integrity", () => {it("assembles real inventory fragments and retains every citation", async () => {const parent = await createTestTempDirectory("rea-artifact-fragments-");diff --git a/tests/boundary/filesystem/artifactZipIntegrity.test.ts b/tests/boundary/filesystem/artifactZipIntegrity.test.tsindex cf7dcd595..e02c22674 100644--- a/tests/boundary/filesystem/artifactZipIntegrity.test.ts+++ b/tests/boundary/filesystem/artifactZipIntegrity.test.ts@@ -39,6 +39,7 @@ it("completes an empty ZIP extraction with an empty identity", async () => {});const legacyControlNames = [+ ["unflagged UTF-8-looking legacy bytes", Buffer.from("café"), false, "caf├⌐"],["legacy ASCII control", Buffer.from("Icon\r"), false, "Icon\r"],["legacy CP437 control",@@ -311,10 +312,13 @@ it("retains duplicate ZIP members without replacing their source identities", asconst target = await parseBinaryTarget(path);if (!target.ok) throw target.error;await withArtifactClient(target.value, async (client) => {- expect(await client.execute("inventory_artifact", {})).toMatchObject({- ok: false,- error: { _tag: "ArtifactOperationError", reason: "path" },- });+ const result = await client.execute("inventory_artifact", {});+ if (!result.ok) throw result.error;+ expect(+ artifactInventoryResultSchema+ .parse(result.value.result)+ .occurrences.filter(({ logical_path }) => logical_path === "x.txt"),+ ).toHaveLength(2);});});