Product case study · November 30, 2026

Ask Claude Code to reject ambiguous ZIP imports

Reproduce a ZIP import with duplicate manifest files, ask Claude Code for a scoped repair, and verify rejection before the importer parses JSON.

Reading time
6 min
Checked
Nov 30, 2026
Two matching ochre file cards in a paper archive box meet a charcoal inspection gate beside a single blue card.
Two manifests need a decision before either becomes input.
Bottom line

A filename is not a unique identifier inside every ZIP. Give the importer an explicit duplicate policy and test it in both archive orders.

Your importer asks a ZIP for manifest.json, parses valid JSON and reports a project name. That sounds successful until you discover that the archive contains two entries with that exact filename. Which project did you just import?

This exercise gives Claude Code a concrete policy to implement: accept exactly one root-level manifest.json; reject zero or multiple matches. We will test the failure ourselves and give the agent a verifier it cannot quietly weaken.

Use Python 3.10 or newer, Bash on Linux, macOS or WSL, and an installed, signed-in Claude Code. Everything happens in memory inside a disposable practice folder. The Python reproduction and reference repair were tested locally with Python 3.14.4; the Claude prompt below is an authored exercise, not a recorded Claude run. Official sources were checked November 30, 2026.

Reproduce the ambiguous import

Create the folder and a deliberately incomplete importer:

zip_lab=$(mktemp -d /tmp/claude-zip.XXXXXX)
cd "$zip_lab"
cat > importer.py <<'PY'
import json
from zipfile import ZipFile


def load_manifest(stream):
    with ZipFile(stream) as archive:
        return json.loads(archive.read("manifest.json"))
PY

Save this as verify_import.py:

from io import BytesIO
import warnings
from zipfile import ZipFile

from importer import load_manifest


def package(entries):
    stream = BytesIO()
    with ZipFile(stream, "w") as archive:
        # Duplicate names are deliberate test input, not a fixture mistake.
        with warnings.catch_warnings():
            warnings.filterwarnings(
                "ignore", message="Duplicate name:.*", category=UserWarning
            )
            for name, payload in entries:
                archive.writestr(name, payload)
    stream.seek(0)
    return stream


first = ("manifest.json", '{"project": "alpha"}')
second = ("manifest.json", '{"project": "beta"}')
cases = [
    ("one manifest", [first, ("notes.txt", "hello")],
     {"project": "alpha"}, None),
    ("missing manifest", [("nested/manifest.json", first[1])],
     None, "Expected one manifest.json; found 0"),
    ("duplicate forward", [first, second],
     None, "Expected one manifest.json; found 2"),
    ("duplicate reversed", [second, first],
     None, "Expected one manifest.json; found 2"),
    ("duplicates before parsing", [first, ("manifest.json", "not JSON")],
     None, "Expected one manifest.json; found 2"),
]
failures = []
for label, entries, expected, error in cases:
    try:
        result = load_manifest(package(entries))
    except Exception as exc:
        if error is not None and type(exc) is ValueError and str(exc) == error:
            print(f"PASS: {label}")
        else:
            failures.append(f"{label}: {type(exc).__name__}: {exc}")
    else:
        if error is None and result == expected:
            print(f"PASS: {label}")
        else:
            failures.append(f"{label}: unexpectedly returned {result!r}")
if failures:
    raise RuntimeError("\n".join(failures))
print("PASS: all five import checks")

Run python3 verify_import.py. The valid case should pass, while the others fail the contract. In the local baseline, the forward duplicate returned beta and reversing the entries returned alpha. The malformed duplicate raised a JSON decoding error instead of the required duplicate error.

Python’s ZIP documentation explicitly discusses duplicate names and supports selecting a specific member with a ZipInfo object. The CPython implementation maintains both a member list and a name lookup. A successful lookup therefore is not a uniqueness check. Do not make your application’s policy depend on which duplicate a particular reader selects.

Give Claude Code the policy and the test

Start claude in the practice folder. Use the project-session lesson if you need help establishing the working directory and permissions. Paste:

Read importer.py and verify_import.py. Run python3 verify_import.py
before editing and report the failures.

Change only importer.py. Keep load_manifest(stream). Accept exactly
one member whose filename is exactly manifest.json at the ZIP root.
For zero or multiple matches, raise ValueError with the message
Expected one manifest.json; found N
where N is the number of matches. Check the count before reading or
parsing a member. Read the selected member by its ZipInfo object.
Keep normal JSON parsing errors for a single malformed manifest.

Do not extract files, rewrite the ZIP, choose the first or last duplicate,
edit the verifier, install packages, commit or delegate. Run the unchanged
verifier after the repair and show the final function and actual output.

Anthropic’s best practices recommend giving Claude an executable check. Here the check expresses a product decision: an ambiguous package must not select its own winner. The prompt’s file restriction still needs review; it is not an enforced sandbox.

The malformed duplicate case matters. A patch that parses a member first could fail for the wrong reason, masking the ambiguity. The verifier demands the count error before any JSON interpretation.

Compare the repair and run it yourself

A reference implementation is:

import json
from zipfile import ZipFile


def load_manifest(stream):
    with ZipFile(stream) as archive:
        matches = [
            member for member in archive.infolist()
            if member.filename == "manifest.json"
        ]
        if len(matches) != 1:
            raise ValueError(
                f"Expected one manifest.json; found {len(matches)}"
            )
        return json.loads(archive.read(matches[0]))

This enumerates entries before selecting one. The documented infolist() method returns member information, and read() accepts that member object. Counting a set of filenames would lose the very duplicates we need to detect.

Exit Claude and run python3 verify_import.py yourself. The reference repair produced:

PASS: one manifest
PASS: missing manifest
PASS: duplicate forward
PASS: duplicate reversed
PASS: duplicates before parsing
PASS: all five import checks

Read the verifier again to confirm it still includes both orders and the invalid JSON payload. A patch that returns a constant could pass the valid example, but it would fail the rejection cases. A patch that rejects every archive would fail the valid example.

If your real import still behaves differently

A KeyError for the missing case usually means the code still performs a name lookup before counting. A JSON error for the duplicate case means it likely reads too early. If the baseline already rejects duplicates, confirm that you are importing the deliberately incomplete importer.py from this folder.

The root-only rule is intentional: nested/manifest.json does not count. Nor does Manifest.json. If your format needs case folding or Unicode normalization, define that separately and add collision tests before changing the comparison. Do not quietly normalize paths and assume they remain unique.

This lab checks one import contract. It does not make arbitrary uploaded ZIPs safe: it has no resource limits, schema validation or extraction policy. Use synthetic files here. When adapting it, start with the archive format your application actually promises and add the limits that environment requires.

Sources

Primary sources checked November 30, 2026:

Put this to work

Why a successful filename lookup does not prove an archive contains one unambiguous input.

Try

Run the disposable Python fixture, then give Claude Code a narrowly scoped repair prompt.

Prove it worked

Run the unchanged verifier and require all five cases to pass.

Keep in view

  • Create a tiny archive with two different manifest.json entries.
  • Ask Claude Code to reject duplicate members before parsing JSON.
  • Verify both entry orders, a missing manifest and a valid import.
Learn the workflow: Start a scoped Claude Code session