All Articles

Valid JSON, Missing Data: CLI Output for AI

Arseniy Potapov
··15 min read·
Valid JSON, Missing Data: CLI Output for AI

An agent can get valid JSON, see the pipeline exit 0 and still act on page one alone. How to make CLI output say partial, and a check that catches it.

In September I ran an experiment with a CLI of my own, and it printed a correct JSON result on stdout. The agent never got to use it. Its host merged stderr into the same stream, and JSON.parse failed on the diagnostic line sitting next to valid data.

The CLI's output was fine. What the consumer received was not. That gap is wider than streams. A CLI result can parse, exit 0 and still fail to say the one thing a decision needs: whether the list you got is the list you asked for.

My own CLIs cap every list by default and say whether the result was truncated, because a first page should never pass for the whole answer. The agent's next move is to narrow the query or follow the cursor. What I hadn't pinned down is how that signal survives the trip to the consumer, and what a wrapper has to say when a fetch-all stops early.

The public gh binary shows the cheapest version of the same failure, and I reproduced it locally.

The Parser Succeeds After the Fetch Fails

The fixture is a loopback server with two pages. Page one returns [{"id": 1}] with a Link header advertising page two. Page two accepts the connection and closes it before sending any response. I pointed gh 2.106.0, the current release at the time of the check, at it with --paginate --slurp. The transcripts below are abbreviated: the real paths are /disconnect/first and /disconnect/second, and the diagnostic carries the request URL.

Shell
gh api "$URL" --paginate --slurp
# stdout: one outer array holding page one: [ [{"id": 1}] ]
# stderr: Get "http://127.0.0.1:PORT/disconnect/second": EOF
# exit:   1

Stdout is valid JSON holding page one. The process exits 1 and says why on stderr, so far so honest. The array is closed anyway. In the source, the slurp writer is installed with a deferred Close, a request error returns before another page starts, and Close writes the final bracket on the way out.

Now put a formatter behind it:

Shell
gh api "$URL" --paginate --slurp | python -m json.tool
# stdout: the same array, pretty-printed
# stderr: the same EOF line
# pipeline exit: 0

Exit 0. Bash reports the status of the last command in a pipeline, and the formatter succeeded. The EOF is still on stderr, but nothing in the status says a fetch failed. With set -o pipefail the same pipeline exits 1. These are separate runs of the same fixture, not one run seen three ways.

Page two disconnects, three runs

A successful formatter turns gh's failed fetch into a pipeline exit 0

Stdout and stderr are the same in every run. Only the status changes, and a default pipeline reports the formatter's.

Three rows, one per separate run of the same fixture, in which page two closes the connection before responding. In every row stdout decodes to the same array holding page one only, [[{"id": 1}]], and stderr holds the same EOF error. Row 1, gh alone: the status is gh's own, exit 1, so the failure is reported. Row 2, gh piped to python -m json.tool: Bash reports the last command's status, the formatter's, and the pipeline exits 0, so the failure is hidden. Row 3, the same pipe with set -o pipefail: Bash reports the rightmost command that failed, gh, and the pipeline exits 1. Only the status column differs between the rows.

Local reproduction: the official gh 2.106.0 release binary against a loopback server whose second page closes the connection before sending a response. Three separate runs of the same fixture in Bash, formatter python -m json.tool. A bounded software check, not an agent benchmark.

Stdout is shown decoded; in rows 2 and 3 the formatter pretty-prints it. Stderr is abbreviated: the full line is Get "http://127.0.0.1:PORT/disconnect/second": EOF. Which command a pipeline takes its status from is Bash's documented rule, not a separate measurement.

Data behind this figure
RunCommandStatus measured forStdout, decodedStderrExit
1. gh alonegh api "$URL" --paginate --slurpgh process[[{"id":1}]]Get "http://127.0.0.1:PORT/disconnect/second": EOF1
2. Piped to a formattergh api "$URL" --paginate --slurp | python -m json.tooldefault Bash pipeline (status of the last command, json.tool)[[{"id":1}]]Get "http://127.0.0.1:PORT/disconnect/second": EOF0
3. Same pipe, pipefail onset -o pipefail; gh api "$URL" --paginate --slurp | python -m json.toolBash pipeline with pipefail (status of the rightmost command to exit non-zero)[[{"id":1}]]Get "http://127.0.0.1:PORT/disconnect/second": EOF1

Three separate runs of the same page-two disconnect fixture, not one run seen three ways. Stdout parses as JSON in all three.

I need the producer's exit status alongside the parsed data. The formatter's status doesn't tell me whether the fetch finished.

To run it yourself:

  1. You need Python 3 and Bash. Download the official gh 2.106.0 release archive for your platform from the cli/cli releases page and unpack it.
  2. Save the script from the appendix as reproduce.py. There's no public copy, so the appendix holds the whole file.
  3. Run python3 reproduce.py --binary /absolute/path/to/gh --output receipt.json.

The script starts the loopback fixture on an ephemeral port, gives gh a dummy token and an isolated config directory, and runs five cases: the two-page success, the page-two disconnect, a page-two HTTP 503, the disconnect through the formatter, and the same pipeline under pipefail. It prints a receipt with each exit code, stdout, stderr and the paths requested. Expect exit 0 for the success, 1 for the direct disconnect, 0 for the default pipeline and 1 with pipefail. The 503 case is in the appendix table: its output is page one followed by the error object, so parsing can't be the acceptance test even when everything arrives.

My rule from this: capture stdout, stderr and the producer's status separately, or use pipefail. Then go further than status, because status can't tell you why retrieval stopped.

Name the Reason Retrieval Stopped

Preserving the exit code is the first repair, and a thin one. An exit code says the fetch failed. It doesn't say whether the list ended, a budget ran out, or a guard fired. Those are different facts, and a caller deciding "is this everything?" needs to tell them apart.

The MCP TypeScript client makes the problem concrete. Its aggregate list helper, in the revision I read, keeps requesting pages while the cursor is defined, and an empty string counts as defined.

It stops in three ways. If a configured page cap is reached, it throws. If a page repeats the previous page's items and cursor, it breaks, treating that as the server making no progress. Otherwise the server's cursor runs out.

After the loop it deletes nextCursor and returns. So the caller sees an aggregate without a cursor after exhaustion and after the repeated-page guard alike. A safety policy and a server's "that was everything" produce the same output.

The endpoints I checked don't agree on what "the end" looks like either:

Source How the end is signalled Trap
MCP list operations nextCursor is absent An empty string is a valid cursor, so a truthiness check stops early
CloudWatch GetLogEvents The returned directional token equals the one you sent Empty or partial pages don't mean the end
CloudWatch FilterLogEvents nextToken is absent An empty page can still carry a token, and limit bounds a page, not the matches

Transplanting one rule onto another endpoint is how you build a client that stops early on one and spins forever on the other. GetLogEvents with startFromHead=true and no end time can keep going as long as ingestion outpaces reading. Its tokens expire after 24 hours, so "resumable" has a shelf life.

Budget stops are the ones I worry about most in agent work, because they're deliberate and so they feel safe. A wrapper that stops at 20 pages to protect the context window has made a sensible call. If it then returns the 20 pages with nextCursor stripped, as the MCP client's finalize step does after its guard, the caller can't tell a sensible stop from the end of the data. The page cap that throws is, oddly, the more honest design: it fails loudly instead of returning something plausible.

So the wrapper's job is to translate each endpoint's rule into one vocabulary of stop reasons and say it in the output, without changing what the upstream token means. My working set: server_end, request_error, no_progress, page_limit, time_budget, byte_budget. Only the first is the service saying "done". The rest are the client stopping, and the output must say so. An empty page alone proves none of them.

Define CLI Output for Agents Around the Request

In my CLIs this started as a smaller rule. taktcli caps every list by default and returns one envelope shape, {totalCount, truncated, order, rows}, after four commands had four different shapes. Mission Control goes further and refuses to fetch everything implicitly. I converged on those because I wanted the agent to narrow the query or follow the cursor, and never treat the first page as the whole answer. That's an average of what worked across about fifteen CLIs, not a standard.

The CLI Agent Spec catalogues pipeline exit masking, pagination and partial failure; here I follow one reproduced failure through to a checker.

For a fetch-all mode, the envelope needs to carry the request, not just the rows. Here's the sketch. It's pseudocode for a wrapper's output, not something gh emits:

JSON
{
  "schema": 1,
  "status": "partial",
  "stop_reason": "request_error",
  "pages_read": 1,
  "scope": {"url": "/items", "per_page": 1},
  "consistency": "unspecified",
  "error": {"code": "transport_eof", "retryable": true},
  "continuation": {"cursor": "", "bound_to": "scope", "expires": null},
  "projection": {"fields": ["id"], "clipped": []},
  "items": [{"id": 1}]
}

The rules behind it matter more than the field names:

  1. Three states plus unknown. complete means the service declared exhaustion for this exact query and the required evidence arrived. partial means data is retained but the traversal didn't finish, including a request error after page one. error means nothing usable. If traversal state is unknown, the output says unknown and doesn't guess.
  2. Server end is necessary, not sufficient. A fetch-all also needs the scope to match what was requested and every required field to be present. Required fields must survive projection as well as successful traversal. You can't infer scanned scope or expected totals from the IDs you got back. An unknown count stays unknown.
  3. Single-page success is not exhaustion. A command asked for one page can succeed without the collection ending. The mode the caller requested belongs in the output.
  4. Keep the empty cases apart. Absent, null, empty list, empty string, false and 0 each get a schema-defined meaning. A valid empty upstream cursor survives inside continuation instead of being normalized into nothing.
  5. Offer resume only when the API can. The continuation says what it's bound to, its direction and when it expires.

Consistency is a separate question from completeness, and the envelope keeps them apart. complete says the traversal ran to the service's declared end. It doesn't say the records form a snapshot. Records can arrive while you page, which is exactly why GetLogEvents can outrun a reader, and a service that doesn't promise point-in-time reads gives you a walk, not a photograph. So consistency holds what the service's documentation guarantees, or unspecified. A caller that needs a snapshot checks that field. A caller that only needs "everything the service would return for this query" checks status.

Exit codes follow from the house standard I converged on: 0 for success, 1 when the API refused, 2 for transport, timeout and 5xx. The failed fetch-all cases above already fit exit 2, with the rows retained and the machine-readable status on stdout. The open question is a deliberate budget stop. Whether a 20-page stop is a success depends on the mode the caller asked for, so the exit code for it is a decision for your tool.

One known gap in my own tools: taktcli drops the partial data when GraphQL answers with both data and errors. maestro does the right thing and prints the partial data with exit 1. The first loses work the server already did.

Check What the Host Actually Receives

Back to the September run. The CLI was an experimental one I built for a benchmark, not gh. I injected an HTTP 503 into a frozen replay of a public repository. The CLI printed a correct JSON envelope on stdout and the diagnostic on stderr. The agent's host combined the two streams, and the first JSON.parse failed on the diagnostic line. The agent re-fetched three details, two of which it already had. The final answer was exact. It was one run, so it's an observation and not an error rate.

The lesson in my CLI guide is to test what the consuming host delivers. A host can merge streams, clip a payload, or report the status of the last command in a pipe. Separate streams are a property of the CLI. What reaches the model is a property of the harness. I keep errors as JSON on stderr, and for fetch-all I also keep the machine-readable status in stdout, so incompleteness isn't discoverable only on a channel the host may drop.

My checker had a type problem too. Before the construction runs in the same experiment, I replaced Python dictionary equality in my checker with a typed JSON comparison, because ordinary equality treats False and 0 as the same value. After the change, corruption controls that flipped a false to a true, or a false to a zero, were rejected by both adapters. The primary task oracles were already strict. The weak spot was my own checker, which would have passed that corruption before a single subject ran.

That's why the acceptance list for a result I hand to an agent is short, and why its last line is about types:

  • the schema validates, with a version
  • the producer's status is preserved, not the formatter's
  • status and stop_reason agree
  • the scope equals what I requested, compared without coercing true into 1
  • every field the decision needs is present, unclipped, with its real type

Bound the Evidence Without Hiding the Bound

Everything so far is about traversal. Projection is a separate axis, and it's the one that fails quietly. A field you selected out, a value clipped at 8,000 characters and a record that never arrived are three different absences. Put them in different places in the output: projection.fields for what you chose, projection.clipped for values cut short, status and stop_reason for missing records. A narrow projection can be complete for a narrow question and useless for a broader one.

The consumer clips too, and where depends on the tool and its configuration. Claude Code documents a configurable limit on MCP tool output and file-backed handling for large text results, so what the model sees can differ from what your CLI printed. A preview in a UI doesn't prove what the model received. Look at the payload that arrived at the consumer, not at the terminal. CLI or MCP covers the cost side: recorded bytes didn't establish what the model saw.

LangChain reported a related result from a browser agent: after they capped snapshots at 8,000 characters, agents fetched the page again and cost per passed task stayed flat. That's one team's report, and it doesn't say truncation always costs more. It does say that a smaller response isn't automatically a cheaper task.

Expose the bound and give the agent a way to get the rest. A big artifact goes to a file and the command prints only the path. A truncated list says truncated: true and how to narrow it, and a clipped field says which field. When the output hides its own limit, the agent's only move is to ask again, and it asks the same question. When one field names the limit, it can change the question. Measure refetches per task on your own traffic before and after. The five-question task check walks through the cursor handoff in detail.

Make One Failed Fetch Fail Acceptance

Here's the check. Take the same page-two disconnect and run it through the path your agent really uses: the same shell, the same wrapper, the same host. Keep stdout, stderr, the producer status and the pipeline status. Then run the two-page success as a control, because a pass needs a positive control next to it.

The raw gh output isn't the envelope, so the wiring has one substitution point. Your wrapper emits the envelope from the contract section. The validator takes what the host delivered: its stdout, the producer's exit status and the scope you asked for. It's my recommendation, separate from the gh reproduction, and it runs in this order:

  1. Reject a nonzero producer status.
  2. Parse stdout and require an object with the integer schema version 1.
  3. Require status: complete and stop_reason: server_end.
  4. Compare the returned scope to the requested one, type by type.
  5. Require projection.fields and projection.clipped to be lists of field names, reject any required field that is clipped or missing from fields.
  6. Check every item is an object and every required field has its declared type: str, int or bool, kept apart, so false never passes for an integer ID and null never passes for a string.

It returns a list of reasons instead of raising, so a malformed envelope is a rejection and never a crash. Anything beyond those three scalar types falls outside this small contract, and the validator rejects the declaration instead of guessing. These are the nineteen controls I ran against it:

complete, two pages                -> ACCEPT
healthy empty                      -> ACCEPT
page-two disconnect (partial)      -> ['producer exited 1']
partial envelope, wrapper exit 0   -> ['status=partial stop_reason=request_error']
wrong type id: false               -> ['item 0: id is not an integer']
required field clipped             -> ["required field clipped: ['id']"]
raw gh --slurp output              -> ['producer exited 1']
item null                          -> ['item 0 is not an object']
items [[id]]                       -> ['item 0 is not an object']
schema true                        -> ['unknown schema version']
scope per_page true                -> ['scope differs from the request']
scope different                    -> ['scope differs from the request']
str field is null                  -> ['item 0: name is not a string']
str field ok                       -> ACCEPT
bool field is 0                    -> ['item 0: enabled is not a boolean']
malformed clipped entry            -> ['projection.fields and projection.clipped must be lists of field names']
projection.fields missing          -> ['projection.fields and projection.clipped must be lists of field names']
id not in projection.fields        -> ["required field not in projection.fields: ['id']"]
unsupported type declared          -> ["unsupported required-field declaration: ['id']"]

The appendix has a driver, check_host.py, that connects the pieces. It starts the same loopback fixture, runs a consumer command while the server is alive, captures stdout, stderr and the producer's exit status, builds the envelope from what it observed and the scope it requested, and calls the validator. Two spots are yours to replace: consume() is the command your host runs, and to_envelope() is a stand-in for your wrapper. Validation receives the host-delivered payload. This is the real output against gh 2.106.0, run as python3 check_host.py --binary /absolute/path/to/gh:

success    producer exit 0, stderr ''
           verdict: ACCEPT
           control healthy empty: ACCEPT
           control wrong ID type: ['item 0: id is not an integer']
           control clipped ID: ["required field clipped: ['id']"]
disconnect producer exit 1, stderr 'Get "http://127.0.0.1:33803/disconnect/s'
           verdict: ['producer exited 1']

The three controls under the success case mutate its envelope. The adapter decides complete or partial from the producer's status, never from the fixture's name.

The healthy empty collection is accepted, and that matters. An empty items with status: complete and stop_reason: server_end is a real answer. An empty items after a request error is not, and it's the failure I'd least like an agent to read as "nothing there".

The validator checks the declared contract and the shape of the evidence. It can't tell whether a producer's claims are true, and a wrapper that writes complete after a silent loss still passes. That's why the producer status and the host-level run come first.

A budgeted partial response is still useful. An agent can sample the first page of a huge list and act on it. It just can't use that response to conclude "there are no more," and the check above is what stops it.

Run it against your own host this week. If the disconnect gets through, you've found it in an afternoon instead of after a wrong answer.

Methodology and full results

The local reproduction used the official gh 2.106.0 Linux amd64 release binary against a loopback server on an ephemeral port, with an isolated configuration directory and a dummy token. No authenticated GitHub requests were made. Page one carried a Link header advertising page two. The successful control served both pages. The disconnect case closed page two's connection before sending a response. The 503 case returned a JSON error body, and the output is page one followed by {"message": "fixture unavailable"}: parseable, one array, with an error object among the pages.

Case Process measured Exit Parses Decoded stdout
Two successful pages gh 0 yes pages one and two
Page-two disconnect gh 1 yes page one only
Page-two HTTP 503 gh 1 yes page one, then the error object
Disconnect through JSON formatter default Bash pipeline 0 yes page one only
Same pipeline with pipefail Bash pipeline 1 yes page one only

Stderr held the upstream error in every failing case. The measurements describe a bounded software check, not an agent benchmark.

reproduce.py

Python
"""Exercise a gh binary against bounded loopback pagination failures."""
import argparse
import http.server
import json
import os
from pathlib import Path
import socket
import subprocess
import sys
import tempfile
import threading


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--binary", required=True)
    parser.add_argument("--output", required=True)
    args = parser.parse_args()
    binary = str(Path(args.binary).resolve())
    records = []

    class Handler(http.server.BaseHTTPRequestHandler):
        def log_message(self, *args):
            pass

        def do_GET(self):
            mode = self.path.split("/")[1]
            second = "/second" in self.path
            self.server.requests.append(self.path)
            if second and mode == "disconnect":
                self.connection.shutdown(socket.SHUT_RDWR)
                self.connection.close()
                return
            status = 503 if second and mode == "http503" else 200
            body = {"message": "fixture unavailable"} if status == 503 else [{"id": 2 if second else 1}]
            payload = json.dumps(body).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(payload)))
            if not second:
                self.send_header("Link", f'<http://127.0.0.1:{self.server.server_port}/{mode}/second>; rel="next"')
            self.end_headers()
            self.wfile.write(payload)

    with tempfile.TemporaryDirectory() as home, http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
        server.requests = []
        threading.Thread(target=server.serve_forever, daemon=True).start()
        env = {"PATH": os.defpath, "HOME": home, "GH_CONFIG_DIR": home,
               "GH_TOKEN": "local-fixture-not-a-credential", "GH_PROMPT_DISABLED": "1",
               "GH_NO_UPDATE_NOTIFIER": "1", "NO_COLOR": "1"}
        version = subprocess.run([binary, "--version"], capture_output=True, text=True, env=env, check=True).stdout.splitlines()[0]
        for mode, pipeline in [("success", "direct"), ("disconnect", "direct"), ("http503", "direct"), ("disconnect", "default"), ("disconnect", "pipefail")]:
            server.requests.clear()
            url = f"http://127.0.0.1:{server.server_port}/{mode}/first"
            command = [binary, "api", url, "--paginate", "--slurp"]
            if pipeline != "direct":
                script = ('set -o pipefail; ' if pipeline == "pipefail" else '') + '"$1" api "$2" --paginate --slurp | "$3" -m json.tool'
                command = ["bash", "-c", script, "fixture", binary, url, sys.executable]
            result = subprocess.run(command, capture_output=True, text=True, env=env, timeout=20)
            try:
                parsed = json.loads(result.stdout)
                valid = True
            except ValueError:
                parsed, valid = None, False
            records.append({"case": mode, "pipeline": pipeline, "exit": result.returncode,
                            "valid_json": valid, "parsed": parsed, "stdout": result.stdout,
                            "stderr": result.stderr, "requests": list(server.requests)})
        server.shutdown()
    output = {"version": version, "python": sys.version, "records": records}
    Path(args.output).write_text(json.dumps(output, indent=2) + "\n")
    print(json.dumps(output, indent=2))


if __name__ == "__main__":
    main()

accept_fetch_all.py

Python
import json

SUPPORTED = {str: "a string", int: "an integer", bool: "a boolean"}  # supported field types
REQUIRED = {"id": int}        # field -> type the decision needs


def is_int(v):
    return type(v) is int  # excludes bool


def same(a, b):
    """Equality that never lets True equal 1 or 1.0 equal 1."""
    if type(a) is not type(b):
        return False
    if isinstance(a, dict):
        return a.keys() == b.keys() and all(same(a[k], b[k]) for k in a)
    if isinstance(a, list):
        return len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))
    return a == b


def names(value):
    """A list of field-name strings, or None when malformed."""
    if isinstance(value, list) and all(type(n) is str for n in value):
        return set(value)
    return None


def accept_fetch_all(stdout, producer_exit, scope, required=REQUIRED):
    """Return a list of rejection reasons. An empty list means accept.

    Checks the declared contract and the shape of the evidence.
    It cannot tell whether the producer's claims are true."""
    bad = [f for f, t in required.items() if type(f) is not str or t not in SUPPORTED]
    if bad:
        return [f"unsupported required-field declaration: {bad}"]
    if producer_exit != 0:
        return [f"producer exited {producer_exit}"]
    try:
        out = json.loads(stdout)
    except ValueError:
        return ["stdout is not JSON"]
    if not isinstance(out, dict):
        return ["not an envelope object"]
    if not is_int(out.get("schema")) or out["schema"] != 1:
        return ["unknown schema version"]
    if out.get("status") != "complete" or out.get("stop_reason") != "server_end":
        return [f"status={out.get('status')} stop_reason={out.get('stop_reason')}"]
    if not same(out.get("scope"), scope):
        return ["scope differs from the request"]
    proj = out.get("projection")
    if not isinstance(proj, dict):
        return ["projection missing"]
    fields, clipped = names(proj.get("fields")), names(proj.get("clipped"))
    if fields is None or clipped is None:
        return ["projection.fields and projection.clipped must be lists of field names"]
    if clipped & set(required):
        return [f"required field clipped: {sorted(clipped & set(required))}"]
    if set(required) - fields:
        return [f"required field not in projection.fields: {sorted(set(required) - fields)}"]
    items = out.get("items")
    if not isinstance(items, list):
        return ["items missing"]
    reasons = []
    for n, item in enumerate(items):
        if not isinstance(item, dict):
            reasons.append(f"item {n} is not an object")
            continue
        for field, typ in required.items():
            if field not in item:
                reasons.append(f"item {n} lacks {field}")
            elif type(item[field]) is not typ:
                reasons.append(f"item {n}: {field} is not {SUPPORTED[typ]}")
    return reasons

check_host.py

Python
"""Run a consumer command against the loopback fixture and validate what it delivers.

    python3 check_host.py --binary /absolute/path/to/gh

Needs accept_fetch_all.py in the same directory."""
import argparse
import http.server
import json
import os
import socket
import subprocess
import tempfile
import threading
from pathlib import Path

from accept_fetch_all import accept_fetch_all


class Handler(http.server.BaseHTTPRequestHandler):  # same fixture as reproduce.py
    def log_message(self, *args):
        pass

    def do_GET(self):
        mode = self.path.split("/")[1]
        second = "/second" in self.path
        if second and mode == "disconnect":
            self.connection.shutdown(socket.SHUT_RDWR)
            self.connection.close()
            return
        payload = json.dumps([{"id": 2 if second else 1}]).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(payload)))
        if not second:
            self.send_header("Link", f'<http://127.0.0.1:{self.server.server_port}/{mode}/second>; rel="next"')
        self.end_headers()
        self.wfile.write(payload)


def consume(binary, url, env):
    """REPLACE THIS with the command your host really runs (your wrapper, a pipeline, a harness).
    It must return what the host delivers: stdout, stderr and the producer's exit status."""
    r = subprocess.run([binary, "api", url, "--paginate", "--slurp"],
                       capture_output=True, text=True, env=env, timeout=20)
    return r.stdout, r.stderr, r.returncode


def to_envelope(stdout, exit_code, scope):
    """DEMO ADAPTER standing in for your wrapper. It builds the contract envelope from what
    was observed: the producer's status decides complete or partial, never the fixture name."""
    try:
        pages = json.loads(stdout)
    except ValueError:
        pages = []
    items = [i for page in pages if isinstance(page, list) for i in page]
    done = exit_code == 0
    return {"schema": 1, "status": "complete" if done else "partial",
            "stop_reason": "server_end" if done else "request_error",
            "pages_read": len(pages), "scope": scope,
            "projection": {"fields": ["id"], "clipped": []}, "items": items}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--binary", required=True)
    binary = str(Path(ap.parse_args().binary).resolve())
    with tempfile.TemporaryDirectory() as home, http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
        threading.Thread(target=server.serve_forever, daemon=True).start()
        env = {"PATH": os.defpath, "HOME": home, "GH_CONFIG_DIR": home,
               "GH_TOKEN": "local-fixture-not-a-credential", "GH_PROMPT_DISABLED": "1",
               "GH_NO_UPDATE_NOTIFIER": "1", "NO_COLOR": "1"}
        for mode in ("success", "disconnect"):
            url = f"http://127.0.0.1:{server.server_port}/{mode}/first"
            stdout, stderr, code = consume(binary, url, env)   # the host-delivered payload
            scope = {"url": url, "paginate": True}             # what we asked for
            envelope = json.dumps(to_envelope(stdout, code, scope))
            print(f"{mode:10} producer exit {code}, stderr {stderr.strip()[:40]!r}")
            print(f"{'':10} verdict:", accept_fetch_all(envelope, code, scope) or "ACCEPT")
            if mode == "success":
                good = json.loads(envelope)
                for name, change in [
                    ("healthy empty", {"items": []}),
                    ("wrong ID type", {"items": [{"id": False}]}),
                    ("clipped ID", {"projection": {"fields": ["id"], "clipped": ["id"]}})]:
                    verdict = accept_fetch_all(json.dumps({**good, **change}), 0, scope)
                    print(f"{'':10} control {name}:", verdict or "ACCEPT")
        server.shutdown()


if __name__ == "__main__":
    main()